diff --git a/go/cmswebhook/middleware.go b/go/cmswebhook/middleware.go index e51a3d8..0fd7215 100644 --- a/go/cmswebhook/middleware.go +++ b/go/cmswebhook/middleware.go @@ -1,6 +1,7 @@ package cmswebhook import ( + "context" "encoding/json" "io" "net/http" @@ -8,16 +9,17 @@ import ( type MiddlewareConfig struct { Secret []byte - Logger func(format string, v ...any) + Logger func(ctx context.Context, format string, v ...any) } func Middleware(config MiddlewareConfig) func(http.Handler) http.Handler { if config.Logger == nil { - config.Logger = func(format string, v ...any) {} + config.Logger = func(ctx context.Context, format string, v ...any) {} } return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() body, err := io.ReadAll(r.Body) if err != nil { jsonResp(w, http.StatusUnprocessableEntity, map[string]string{"error": "unprocessable entity"}) @@ -25,14 +27,12 @@ func Middleware(config MiddlewareConfig) func(http.Handler) http.Handler { } sig := r.Header.Get(SignatureHeader) - config.Logger("webhook: received: sig=%s", sig) + config.Logger(ctx, "cms webhook: received: sig=%s, body=%s", sig, body) if !validateSignature(sig, body, config.Secret) { jsonResp(w, http.StatusUnauthorized, map[string]string{"error": "unauthorized"}) return } - config.Logger("webhook: body: %s", body) - p := &Payload{} if err := json.Unmarshal(body, p); err != nil { jsonResp(w, http.StatusBadRequest, map[string]string{"error": "invalid payload"}) @@ -41,8 +41,7 @@ func Middleware(config MiddlewareConfig) func(http.Handler) http.Handler { p.Body = body p.Sig = sig - ctx := AttachPayload(r.Context(), p) - next.ServeHTTP(w, r.WithContext(ctx)) + next.ServeHTTP(w, r.WithContext(AttachPayload(ctx, p))) }) } } diff --git a/go/marshaling_test.go b/go/marshaling_test.go index 275646d..7101a93 100644 --- a/go/marshaling_test.go +++ b/go/marshaling_test.go @@ -26,6 +26,7 @@ func TestItem_Unmarshal(t *testing.T) { III *int `cms:"iii,,metadata,includezero"` JJJ []Tag `cms:"jjj"` KKK *Value `cms:"kkk"` + LLL *Tag `cms:"lll"` } s := S{} @@ -42,6 +43,7 @@ func TestItem_Unmarshal(t *testing.T) { {Key: "iii"}, {Key: "jjj", Value: []any{map[string]any{"id": "xxx", "name": "tag"}}}, {Key: "kkk", Value: []any{map[string]any{"id": "xxx", "name": "tag"}}}, + {Key: "lll", Value: map[string]any{"id": "xxx", "name": "tag"}}, }, MetadataFields: []*Field{ {Key: "eee", Value: true}, @@ -60,6 +62,7 @@ func TestItem_Unmarshal(t *testing.T) { III: nil, JJJ: []Tag{{ID: "xxx", Name: "tag"}}, KKK: &Value{value: []any{map[string]any{"id": "xxx", "name": "tag"}}}, + LLL: &Tag{ID: "xxx", Name: "tag"}, }, s) // no panic