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.
 
 
 

64 lines
1.6 KiB

  1. package handlers
  2. import (
  3. "net/http"
  4. )
  5. // ChainableHandler is a valid Handler interface, and adds the possibility to
  6. // chain other handlers.
  7. type ChainableHandler interface {
  8. http.Handler
  9. Chain(http.Handler) ChainableHandler
  10. ChainFunc(http.HandlerFunc) ChainableHandler
  11. }
  12. // Default implementation of a simple ChainableHandler
  13. type chainHandler struct {
  14. http.Handler
  15. }
  16. func (this *chainHandler) ChainFunc(h http.HandlerFunc) ChainableHandler {
  17. return this.Chain(h)
  18. }
  19. // Implementation of the ChainableHandler interface, calls the chained handler
  20. // after the current one (sequential).
  21. func (this *chainHandler) Chain(h http.Handler) ChainableHandler {
  22. return &chainHandler{
  23. http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  24. // Add the chained handler after the call to this handler
  25. this.ServeHTTP(w, r)
  26. h.ServeHTTP(w, r)
  27. }),
  28. }
  29. }
  30. // Convert a standard http handler to a chainable handler interface.
  31. func NewChainableHandler(h http.Handler) ChainableHandler {
  32. return &chainHandler{
  33. h,
  34. }
  35. }
  36. // Helper function to chain multiple handler functions in a single call.
  37. func ChainHandlerFuncs(h ...http.HandlerFunc) ChainableHandler {
  38. return &chainHandler{
  39. http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  40. for _, v := range h {
  41. v(w, r)
  42. }
  43. }),
  44. }
  45. }
  46. // Helper function to chain multiple handlers in a single call.
  47. func ChainHandlers(h ...http.Handler) ChainableHandler {
  48. return &chainHandler{
  49. http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  50. for _, v := range h {
  51. v.ServeHTTP(w, r)
  52. }
  53. }),
  54. }
  55. }