Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"math/rand"
"net/http"
"os"
"strings"

"github.com/gorilla/mux"
"github.com/rs/cors"
Expand All @@ -21,6 +22,30 @@ type Greeting struct {
Greeting string `json:"greeting"`
}

func AuthMiddleware(apiKey string, next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}

authHeaderParts := strings.Split(authHeader, " ")
if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != "bearer" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}

token := authHeaderParts[1]
if token != apiKey {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}

next.ServeHTTP(w, r)
}
}

func main() {
var greetings []*Greeting
err := json.Unmarshal(greetingsJson, &greetings)
Expand Down Expand Up @@ -57,6 +82,29 @@ func main() {
}
}).Methods("GET")

router.HandleFunc("/greetings", AuthMiddleware(os.Getenv("ADMIN_API_KEY"), func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}

var newGreeting Greeting
err := json.NewDecoder(r.Body).Decode(&newGreeting)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

greetings = append(greetings, &newGreeting)

w.WriteHeader(http.StatusCreated)
_, err = fmt.Fprintf(w, "Greeting added successfully")
if err != nil {
http.Error(w, "Failed to write response", http.StatusInternalServerError)
return
}
})).Methods("POST")

c := cors.New(cors.Options{
AllowedOrigins: []string{
"http://greetings.kylepenfound.com",
Expand Down
70 changes: 70 additions & 0 deletions main_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
package main

import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"

"github.com/gorilla/mux"
"gotest.tools/v3/assert"
)

Expand Down Expand Up @@ -49,3 +54,68 @@ func TestFormatResponse(t *testing.T) {
formatted := FormatResponse(g)
assert.Equal(t, "{\"greeting\":\"Hello, World!\"}", formatted)
}

func TestAddGreetingEndpoint(t *testing.T) {
err := os.Setenv("ADMIN_API_KEY", "testapikey")
if err != nil {
t.Fatalf("Could not set environment variable: %v", err)
}

router := mux.NewRouter()
var greetings []*Greeting

router.HandleFunc("/greetings", AuthMiddleware(os.Getenv("ADMIN_API_KEY"), func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}

var newGreeting Greeting
err := json.NewDecoder(r.Body).Decode(&newGreeting)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

greetings = append(greetings, &newGreeting)

w.WriteHeader(http.StatusCreated)
_, err = fmt.Fprintf(w, "Greeting added successfully")
if err != nil {
http.Error(w, "Failed to write response", http.StatusInternalServerError)
return
}
})).Methods("POST")

// Create a request to the /greetings endpoint
newGreeting := Greeting{Language: "test", Greeting: "Test Greeting"}
requestBody, _ := json.Marshal(newGreeting)

req, err := http.NewRequest("POST", "/greetings", bytes.NewBuffer(requestBody))
if err != nil {
t.Fatalf("Could not create request: %v", err)
}

req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer testapikey")

// Create a recorder to examine the response
rec := httptest.NewRecorder()

// Call the ServeHTTP method directly and pass the request and recorder
router.ServeHTTP(rec, req)

// Check the response code
if rec.Code != http.StatusCreated {
t.Errorf("Expected status code %d, got %d", http.StatusCreated, rec.Code)
}

// Check the response body
expectedBody := "Greeting added successfully"
if !strings.Contains(rec.Body.String(), expectedBody) {
t.Errorf("Expected body to contain %q, got %q", expectedBody, rec.Body.String())
}

// Check that the greeting was actually added (this part is tricky without persistence)
// One way would be to capture the greetings slice and compare it. For now, we skip this
}