wrap.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536
  1. package http
  2. import (
  3. "net/http"
  4. kitlog "github.com/go-kit/kit/log"
  5. )
  6. type MiddlewareFunc func(next http.Handler) http.Handler
  7. type HandlerFuncWithErr func(w http.ResponseWriter, r *http.Request) error
  8. func WrapWithError(f HandlerFuncWithErr, log kitlog.Logger) http.HandlerFunc {
  9. return func(w http.ResponseWriter, r *http.Request) {
  10. if err := f(w, r); err != nil {
  11. log.Log("event", "error", "msg", "could not serve HTTP request", "err", err, "path", r.URL.Path)
  12. http.Error(w, err.Error(), http.StatusInternalServerError)
  13. }
  14. }
  15. }
  16. // Authorize does a very simple header check against a wanted value
  17. // it returns http.StatusUnauthorized if it's false
  18. func Authorize(headerName, wantHeader string) MiddlewareFunc {
  19. return func(next http.Handler) http.Handler {
  20. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  21. hv := r.Header.Get(headerName)
  22. if hv != wantHeader {
  23. http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  24. return
  25. }
  26. next.ServeHTTP(w, r)
  27. })
  28. }
  29. }