No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

chain.go 1.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package phi
  2. // Chain returns a Middlewares type from a slice of middleware handlers.
  3. func Chain(middlewares ...Middleware) Middlewares {
  4. return Middlewares(middlewares)
  5. }
  6. // Handler builds and returns a http.Handler from the chain of middlewares,
  7. // with `h Handler` as the final handler.
  8. func (mws Middlewares) Handler(h Handler) Handler {
  9. return &ChainHandler{mws, h, chain(mws, h)}
  10. }
  11. // HandlerFunc builds and returns a http.Handler from the chain of middlewares,
  12. // with `h Handler` as the final handler.
  13. func (mws Middlewares) HandlerFunc(h HandlerFunc) Handler {
  14. return &ChainHandler{mws, h, chain(mws, h)}
  15. }
  16. // ChainHandler contains middlewares and an endpoint.
  17. type ChainHandler struct {
  18. Middlewares Middlewares
  19. Endpoint Handler
  20. chain Handler
  21. }
  22. // Serve the chain.
  23. func (c *ChainHandler) Serve(ctx Context) {
  24. c.chain.Serve(ctx)
  25. }
  26. // chain builds a http.Handler composed of an inline middleware stack and endpoint
  27. // handler in the order they are passed.
  28. func chain(middlewares []Middleware, endpoint Handler) Handler {
  29. // Return ahead of time if there aren't any middlewares for the chain
  30. if middlewares == nil || len(middlewares) == 0 {
  31. return endpoint
  32. }
  33. // Wrap the end handler with the middleware chain
  34. h := middlewares[len(middlewares)-1](endpoint)
  35. for i := len(middlewares) - 2; i >= 0; i-- {
  36. h = middlewares[i](h)
  37. }
  38. return h
  39. }