middleware.go 3.8 KB

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