Skip to content

Commit

Permalink
customize default echo middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
adwski committed Jan 18, 2024
1 parent 35556a0 commit e1f2e88
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
22 changes: 19 additions & 3 deletions internal/api/middleware/middleware.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,31 @@
package middleware

import (
"github.com/adwski/vidi/internal/generators"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)

func GetEchoWithDefaultMiddleware() *echo.Echo {
e := echo.New()
e.Use(middleware.RequestID()) // TODO configure ID gen func
e.Use(middleware.Logger()) // TODO use with zap.Logger
e.Use(middleware.Recover())

gen := generators.NewID()

e.Use(middleware.RequestIDWithConfig(middleware.RequestIDConfig{
Skipper: middleware.DefaultSkipper,
Generator: gen.GetStringOrPanic,
TargetHeader: echo.HeaderXRequestID,
}))

loggerCfg := middleware.DefaultLoggerConfig // + colorer
// time just like in zap
loggerCfg.CustomTimeFormat = "2006-01-02T15:04:05.000Z0700"
// add level for uniformity
loggerCfg.Format = `{"level":"info","time":"${time_custom}","request_id":"${id}","remote_ip":"${remote_ip}",` +
`"host":"${host}","method":"${method}","uri":"${uri}","user_agent":"${user_agent}",` +
`"status":${status},"error":"${error}","latency":"${latency_human}"` +
`,"bytes_in":${bytes_in},"bytes_out":${bytes_out}}` + "\n"
e.Use(middleware.LoggerWithConfig(loggerCfg))
e.Use(middleware.Recover())
return e
}
16 changes: 16 additions & 0 deletions internal/generators/generators.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,19 @@ func (u *ID) Get() (string, error) {
}
return base64.RawURLEncoding.EncodeToString(uu.Bytes()), nil
}

func (u *ID) GetString() (string, error) {
uu, err := u.gen.NewV4()
if err != nil {
return "", fmt.Errorf("cannot generate new uuid: %w", err)
}
return uu.String(), nil
}

func (u *ID) GetStringOrPanic() string {
uu, err := u.gen.NewV4()
if err != nil {
panic(err)
}
return uu.String()
}

0 comments on commit e1f2e88

Please sign in to comment.