Skip to content

Commit

Permalink
fix(go): reduce log in webhook middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
rot1024 committed Jan 22, 2024
1 parent 9d47b68 commit b8e8155
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
13 changes: 6 additions & 7 deletions go/cmswebhook/middleware.go
Original file line number Diff line number Diff line change
@@ -1,38 +1,38 @@
package cmswebhook

import (
"context"
"encoding/json"
"io"
"net/http"
)

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"})
return
}

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"})
Expand All @@ -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)))
})
}
}
Expand Down
3 changes: 3 additions & 0 deletions go/marshaling_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{}

Expand All @@ -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},
Expand All @@ -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
Expand Down

0 comments on commit b8e8155

Please sign in to comment.