middleware.go 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package http
  2. import (
  3. "fmt"
  4. "net/http"
  5. "runtime/debug"
  6. "strings"
  7. "github.com/ethereum/go-ethereum/metrics"
  8. "github.com/ethereum/go-ethereum/swarm/api"
  9. "github.com/ethereum/go-ethereum/swarm/log"
  10. "github.com/ethereum/go-ethereum/swarm/spancontext"
  11. "github.com/pborman/uuid"
  12. )
  13. // Adapt chains h (main request handler) main handler to adapters (middleware handlers)
  14. // Please note that the order of execution for `adapters` is FIFO (adapters[0] will be executed first)
  15. func Adapt(h http.Handler, adapters ...Adapter) http.Handler {
  16. for i := range adapters {
  17. adapter := adapters[len(adapters)-1-i]
  18. h = adapter(h)
  19. }
  20. return h
  21. }
  22. type Adapter func(http.Handler) http.Handler
  23. func SetRequestID(h http.Handler) http.Handler {
  24. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  25. r = r.WithContext(SetRUID(r.Context(), uuid.New()[:8]))
  26. metrics.GetOrRegisterCounter(fmt.Sprintf("http.request.%s", r.Method), nil).Inc(1)
  27. log.Info("created ruid for request", "ruid", GetRUID(r.Context()), "method", r.Method, "url", r.RequestURI)
  28. h.ServeHTTP(w, r)
  29. })
  30. }
  31. func ParseURI(h http.Handler) http.Handler {
  32. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  33. uri, err := api.Parse(strings.TrimLeft(r.URL.Path, "/"))
  34. if err != nil {
  35. w.WriteHeader(http.StatusBadRequest)
  36. RespondError(w, r, fmt.Sprintf("invalid URI %q", r.URL.Path), http.StatusBadRequest)
  37. return
  38. }
  39. if uri.Addr != "" && strings.HasPrefix(uri.Addr, "0x") {
  40. uri.Addr = strings.TrimPrefix(uri.Addr, "0x")
  41. msg := fmt.Sprintf(`The requested hash seems to be prefixed with '0x'. You will be redirected to the correct URL within 5 seconds.<br/>
  42. Please click <a href='%[1]s'>here</a> if your browser does not redirect you within 5 seconds.<script>setTimeout("location.href='%[1]s';",5000);</script>`, "/"+uri.String())
  43. w.WriteHeader(http.StatusNotFound)
  44. w.Write([]byte(msg))
  45. return
  46. }
  47. ctx := r.Context()
  48. r = r.WithContext(SetURI(ctx, uri))
  49. log.Debug("parsed request path", "ruid", GetRUID(r.Context()), "method", r.Method, "uri.Addr", uri.Addr, "uri.Path", uri.Path, "uri.Scheme", uri.Scheme)
  50. h.ServeHTTP(w, r)
  51. })
  52. }
  53. func InitLoggingResponseWriter(h http.Handler) http.Handler {
  54. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  55. writer := newLoggingResponseWriter(w)
  56. h.ServeHTTP(writer, r)
  57. })
  58. }
  59. func InstrumentOpenTracing(h http.Handler) http.Handler {
  60. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  61. uri := GetURI(r.Context())
  62. if uri == nil || r.Method == "" || (uri != nil && uri.Scheme == "") {
  63. h.ServeHTTP(w, r) // soft fail
  64. return
  65. }
  66. spanName := fmt.Sprintf("http.%s.%s", r.Method, uri.Scheme)
  67. ctx, sp := spancontext.StartSpan(r.Context(), spanName)
  68. defer sp.Finish()
  69. h.ServeHTTP(w, r.WithContext(ctx))
  70. })
  71. }
  72. func RecoverPanic(h http.Handler) http.Handler {
  73. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  74. defer func() {
  75. if err := recover(); err != nil {
  76. log.Error("panic recovery!", "stack trace", debug.Stack(), "url", r.URL.String(), "headers", r.Header)
  77. }
  78. }()
  79. h.ServeHTTP(w, r)
  80. })
  81. }