78 lines
2.2 KiB
Go
78 lines
2.2 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
)
|
|
|
|
func TestAllowOrigin(t *testing.T) {
|
|
const allowedOrigin = "http://127.0.0.1:3000"
|
|
|
|
nextCalled := false
|
|
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
nextCalled = true
|
|
w.WriteHeader(http.StatusNoContent)
|
|
})
|
|
handler := AllowOrigin(allowedOrigin, next)
|
|
|
|
request := httptest.NewRequest(http.MethodPost, "/api/v1/card-to-iban", nil)
|
|
request.Header.Set("Origin", allowedOrigin)
|
|
response := httptest.NewRecorder()
|
|
|
|
handler.ServeHTTP(response, request)
|
|
|
|
if !nextCalled {
|
|
t.Fatal("next handler was not called")
|
|
}
|
|
if got := response.Header().Get("Access-Control-Allow-Origin"); got != allowedOrigin {
|
|
t.Errorf("Access-Control-Allow-Origin = %q, want %q", got, allowedOrigin)
|
|
}
|
|
}
|
|
|
|
func TestAllowOriginDoesNotReflectUnknownOrigin(t *testing.T) {
|
|
handler := AllowOrigin(
|
|
"http://127.0.0.1:3000",
|
|
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}),
|
|
)
|
|
|
|
request := httptest.NewRequest(http.MethodPost, "/api/v1/card-to-iban", nil)
|
|
request.Header.Set("Origin", "https://example.com")
|
|
response := httptest.NewRecorder()
|
|
|
|
handler.ServeHTTP(response, request)
|
|
|
|
if got := response.Header().Get("Access-Control-Allow-Origin"); got != "" {
|
|
t.Errorf("Access-Control-Allow-Origin = %q, want empty", got)
|
|
}
|
|
}
|
|
|
|
func TestAllowOriginHandlesPreflight(t *testing.T) {
|
|
nextCalled := false
|
|
handler := AllowOrigin(
|
|
"http://127.0.0.1:3000",
|
|
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
nextCalled = true
|
|
}),
|
|
)
|
|
|
|
request := httptest.NewRequest(http.MethodOptions, "/api/v1/card-to-iban", nil)
|
|
request.Header.Set("Origin", "http://127.0.0.1:3000")
|
|
request.Header.Set("Access-Control-Request-Method", http.MethodPost)
|
|
response := httptest.NewRecorder()
|
|
|
|
handler.ServeHTTP(response, request)
|
|
|
|
if response.Code != http.StatusNoContent {
|
|
t.Errorf("status = %d, want 204", response.Code)
|
|
}
|
|
if nextCalled {
|
|
t.Error("preflight request reached the next handler")
|
|
}
|
|
if got := response.Header().Get("Access-Control-Allow-Methods"); got != "POST, OPTIONS" {
|
|
t.Errorf("Access-Control-Allow-Methods = %q", got)
|
|
}
|
|
}
|