Skip to content

Commit

Permalink
refactor: add request path to context
Browse files Browse the repository at this point in the history
  • Loading branch information
trim21 committed Oct 18, 2024
1 parent 9c439ba commit 2997789
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 6 deletions.
7 changes: 6 additions & 1 deletion internal/pkg/logger/ctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,22 @@ import (

// https://github.com/uber-go/zap/issues/654

// make RequestKey and unique.
type key string

//nolint:gochecknoglobals
var RequestKey = &struct{}{}
const RequestKey key = "logger.contextKey"

type RequestTrace struct {
IP string
ReqID string
Path string
}

func (r *RequestTrace) MarshalLogObject(enc zapcore.ObjectEncoder) error {
enc.AddString("ip", r.IP)
enc.AddString("request-id", r.ReqID)
enc.AddString("path", r.Path)

return nil
}
Expand Down
8 changes: 3 additions & 5 deletions web/new.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,13 +99,11 @@ func New() *echo.Echo {

app.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
reqID := c.Request().Header.Get(cf.HeaderRequestID)
reqIP := c.RealIP()

c.SetRequest(c.Request().
WithContext(context.WithValue(c.Request().Context(), logger.RequestKey, &logger.RequestTrace{
IP: reqIP,
ReqID: reqID,
IP: c.RealIP(),
ReqID: c.Request().Header.Get(cf.HeaderRequestID),
Path: c.Request().RequestURI,
})))

return next(c)
Expand Down

0 comments on commit 2997789

Please sign in to comment.