diff --git a/internal/stripe/client.go b/internal/stripe/client.go index 1d4495e..bea290d 100644 --- a/internal/stripe/client.go +++ b/internal/stripe/client.go @@ -36,8 +36,8 @@ func (s *Service) CreateSession(ctx context.Context, req CheckoutSessionRequest) quantity = 1 } - params := &stripe.CheckoutSessionParams{} - params.Context = ctx + params := &stripe.CheckoutSessionParams{} + params.Context = ctx params.SuccessURL = stripe.String(s.product.SuccessURL) params.CancelURL = stripe.String(s.product.CancelURL) params.Mode = stripe.String(string(stripe.CheckoutSessionModePayment)) diff --git a/internal/web/handlers.go b/internal/web/handlers.go index 73bca54..8d30b9d 100644 --- a/internal/web/handlers.go +++ b/internal/web/handlers.go @@ -10,16 +10,13 @@ import ( ) func (h *Handler) createCheckoutSession(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost { - w.Header().Set("Allow", http.MethodPost) - http.Error(w, "method not allowed", http.StatusMethodNotAllowed) - return - } - - defer r.Body.Close() - var req stripe.CheckoutSessionRequest + if r.Body != nil { + defer func(body io.ReadCloser) { + _ = body.Close() + }(r.Body) + dec := json.NewDecoder(r.Body) dec.DisallowUnknownFields() @@ -30,9 +27,7 @@ func (h *Handler) createCheckoutSession(w http.ResponseWriter, r *http.Request) http.Error(w, "invalid request payload", http.StatusBadRequest) return } - } - - if dec.More() { + } else if dec.More() { http.Error(w, "unexpected data in request body", http.StatusBadRequest) return } diff --git a/internal/web/handlers_test.go b/internal/web/handlers_test.go index 3ba3318..e05a73a 100644 --- a/internal/web/handlers_test.go +++ b/internal/web/handlers_test.go @@ -110,11 +110,13 @@ func TestCreateCheckoutSessionStripeFailure(t *testing.T) { func TestCreateCheckoutSessionMethodNotAllowed(t *testing.T) { handler := &Handler{checkout: &fakeCheckoutService{}} + mux := http.NewServeMux() + mux.HandleFunc("POST /api/checkout", handler.createCheckoutSession) req := httptest.NewRequest(http.MethodGet, "/api/checkout", http.NoBody) rec := httptest.NewRecorder() - handler.createCheckoutSession(rec, req) + mux.ServeHTTP(rec, req) if rec.Code != http.StatusMethodNotAllowed { t.Fatalf("expected status 405, got %d", rec.Code) diff --git a/internal/web/server.go b/internal/web/server.go index d4d4d94..90545d3 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -25,7 +25,7 @@ func NewServer(cfg config.Config) http.Handler { h := &Handler{cfg: cfg, checkout: checkoutSvc} mux := http.NewServeMux() - mux.HandleFunc("/api/checkout", h.createCheckoutSession) + mux.HandleFunc("POST /api/checkout", h.createCheckoutSession) return mux }