Skip to content

Commit

Permalink
allow to define custom middlewares on webutil.NewServer
Browse files Browse the repository at this point in the history
  • Loading branch information
svenwltr committed Sep 20, 2024
1 parent 81d9d12 commit 514ae43
Showing 1 changed file with 28 additions and 7 deletions.
35 changes: 28 additions & 7 deletions pkg/webutil/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,13 +84,30 @@ func AssetDefaultDev() (AssetPathPrefix, AssetCacheDuration) {
AssetCacheDuration(time.Second)
}

// Middlewares defines all chi middlewares. It needs to be provided as list to dig and not as single middlewares, since
// order matters and dig does not guarantee any ordering. To just append middlewares, you need to append them to the
// ones from `DefaultMiddlewares`
type Middlewares []func(http.Handler) http.Handler

func DefaultMiddlewares() Middlewares {
return Middlewares{
middleware.Compress(7),
chitrace.Middleware(),

// HX-Target is set by HTMX and used by us to decide whether to send the
// whole page or just a frame.
middleware.SetHeader("vary", "hx-target"),
}
}

// Server is a web server targeted on projects that have a user-facing web interface. It supports dependency injection
// using dig.
type Server struct {
AssetFS AssetFS
AssetPathPrefix AssetPathPrefix
AssetCacheDuration AssetCacheDuration
Handlers []Handler
Middlewares Middlewares
}

// ServerParams defines all parameters that are needed for the Server. Its fields can be injected using dig.
Expand All @@ -100,7 +117,8 @@ type ServerParams struct {
AssetFS AssetFS
AssetPathPrefix AssetPathPrefix
AssetCacheDuration AssetCacheDuration
Handlers []Handler `group:"handler"`
Handlers []Handler `group:"handler"`
Middlewares Middlewares `optional:"true"`
}

// Handler is the interface that HTTP handlers need to implement to get picked up and served by the Server.
Expand All @@ -114,11 +132,17 @@ func ProvideHandler(c *dig.Container, fn any) error {
}

func NewServer(p ServerParams) *Server {
middlewares := p.Middlewares
if len(middlewares) == 0 {
middlewares = DefaultMiddlewares()
}

return &Server{
AssetFS: p.AssetFS,
AssetPathPrefix: p.AssetPathPrefix,
AssetCacheDuration: p.AssetCacheDuration,
Handlers: p.Handlers,
Middlewares: middlewares,
}
}

Expand All @@ -135,12 +159,9 @@ func (s *Server) Run(ctx context.Context) error {
ctx = cmdutil.ContextWithDelay(ctx, 5*time.Second)

router := chi.NewRouter()
router.Use(middleware.Compress(7))
router.Use(chitrace.Middleware())

// HX-Target is set by HTMX and used by us to decide whether to send the
// whole page or just a frame.
router.Use(middleware.SetHeader("vary", "hx-target"))
for _, mw := range s.Middlewares {
router.Use(mw)
}

for _, h := range s.Handlers {
h.Register(router)
Expand Down

0 comments on commit 514ae43

Please sign in to comment.