Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

75 lines
2.4KB

  1. /* ----------------------------------------------------------------------
  2. * ______ ___ __
  3. * / ____/___ / | ____ __ ___ __/ /_ ___ ________
  4. * / / __/ __ \/ /| | / __ \/ / / / | /| / / __ \/ _ \/ ___/ _ \
  5. * / /_/ / /_/ / ___ |/ / / / /_/ /| |/ |/ / / / / __/ / / __/
  6. * \____/\____/_/ |_/_/ /_/\__. / |__/|__/_/ /_/\___/_/ \___/
  7. * /____/
  8. *
  9. * (C) Copyright 2015 GoAnywhere (http://goanywhere.io).
  10. * ----------------------------------------------------------------------
  11. * Licensed under the Apache License, Version 2.0 (the "License");
  12. * you may not use this file except in compliance with the License.
  13. * You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing, software
  18. * distributed under the License is distributed on an "AS IS" BASIS,
  19. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. * See the License for the specific language governing permissions and
  21. * limitations under the License.
  22. * ----------------------------------------------------------------------*/
  23. package internal
  24. import (
  25. "net/http"
  26. "github.com/Sirupsen/logrus"
  27. )
  28. type Module struct {
  29. cache http.Handler
  30. stack []func(http.Handler) http.Handler
  31. }
  32. func (self *Module) build() http.Handler {
  33. if self.cache == nil {
  34. next := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {}))
  35. // Activate modules in FIFO order.
  36. for index := len(self.stack) - 1; index >= 0; index-- {
  37. next = self.stack[index](next)
  38. }
  39. self.cache = next
  40. }
  41. return self.cache
  42. }
  43. // Use add the middleware module into the stack chain.
  44. // Supported middleware modules:
  45. // - http.Handler
  46. // - func(http.Handler) http.Handler
  47. func (self *Module) Use(mod interface{}) {
  48. switch H := mod.(type) {
  49. case http.Handler:
  50. handler := func(next http.Handler) http.Handler {
  51. return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  52. H.ServeHTTP(w, req)
  53. next.ServeHTTP(w, req)
  54. })
  55. }
  56. self.stack = append(self.stack, handler)
  57. case func(http.Handler) http.Handler:
  58. self.stack = append(self.stack, H)
  59. default:
  60. logrus.Fatal("Unsupported middleware module passed in.")
  61. }
  62. }
  63. // Implements the net/http Handler interface and calls the middleware stack.
  64. func (self *Module) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  65. self.build().ServeHTTP(w, r)
  66. }