middleware.go 3.5 KB

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