refactor: simplify checkout handler

This commit is contained in:
Ruidy 2025-09-27 11:43:57 +02:00
parent 7e1e6e1df9
commit 4e36eb9692
No known key found for this signature in database
GPG key ID: 705C24D202990805
4 changed files with 12 additions and 15 deletions

View file

@ -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))

View file

@ -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
}

View file

@ -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)

View file

@ -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
}