Skip to content

Commit

Permalink
Merge pull request #146 from movio/request-id-plugin
Browse files Browse the repository at this point in the history
Add request ID plugin
  • Loading branch information
Lucian Jones authored Apr 14, 2022
2 parents 2c940d0 + 8d7fc90 commit 3f1fe52
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ require (
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/gofrs/uuid v4.2.0+incompatible
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
github.com/opentracing/opentracing-go v1.1.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,8 @@ github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/gofrs/uuid v4.2.0+incompatible h1:yyYWMnhkhrKwwr8gAOcOCYxOOscHgDS9yZgBrnJfGa0=
github.com/gofrs/uuid v4.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang-jwt/jwt/v4 v4.0.0 h1:RAqyYixv1p7uEnocuy8P1nru5wprCh/MH2BIlW5z5/o=
Expand Down
43 changes: 43 additions & 0 deletions plugins/request_id.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package plugins

import (
"net/http"

"github.com/gofrs/uuid"
"github.com/movio/bramble"
)

const BrambleRequestHeader = "X-Request-Id"

func init() {
bramble.RegisterPlugin(&RequestIdentifierPlugin{})
}

type RequestIdentifierPlugin struct {
bramble.BasePlugin
}

func (p *RequestIdentifierPlugin) ID() string {
return "request-id"
}

func (p *RequestIdentifierPlugin) middleware(h http.Handler) http.HandlerFunc {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
requestID := r.Header.Get(BrambleRequestHeader)
if requestID == "" {
requestID = uuid.Must(uuid.NewV4()).String()
}

ctx := r.Context()
ctx = bramble.AddOutgoingRequestsHeaderToContext(ctx, BrambleRequestHeader, requestID)
h.ServeHTTP(rw, r.WithContext(ctx))
})
}

func (p *RequestIdentifierPlugin) ApplyMiddlewarePublicMux(h http.Handler) http.Handler {
return p.middleware(h)
}

func (p *RequestIdentifierPlugin) ApplyMiddlewarePrivateMux(h http.Handler) http.Handler {
return p.middleware(h)
}

0 comments on commit 3f1fe52

Please sign in to comment.