router.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package router
  2. import (
  3. "net/http"
  4. "regexp"
  5. "strings"
  6. nanoid "github.com/matoous/go-nanoid/v2"
  7. log "github.com/sirupsen/logrus"
  8. )
  9. const (
  10. xRequestIDHeader = "X-Request-ID"
  11. )
  12. var (
  13. requestIDRe = regexp.MustCompile(`^[A-Za-z0-9_\-]+$`)
  14. )
  15. type RouteHandler func(string, http.ResponseWriter, *http.Request)
  16. type PanicHandler func(string, http.ResponseWriter, *http.Request, error)
  17. type route struct {
  18. Method string
  19. Prefix string
  20. Handler RouteHandler
  21. Exact bool
  22. }
  23. type Router struct {
  24. prefix string
  25. Routes []*route
  26. PanicHandler PanicHandler
  27. }
  28. func (r *route) isMatch(req *http.Request) bool {
  29. if r.Method != req.Method {
  30. return false
  31. }
  32. if r.Exact {
  33. return req.URL.Path == r.Prefix
  34. }
  35. return strings.HasPrefix(req.URL.Path, r.Prefix)
  36. }
  37. func New(prefix string) *Router {
  38. return &Router{
  39. prefix: prefix,
  40. Routes: make([]*route, 0),
  41. }
  42. }
  43. func (r *Router) Add(method, prefix string, handler RouteHandler, exact bool) {
  44. r.Routes = append(
  45. r.Routes,
  46. &route{Method: method, Prefix: r.prefix + prefix, Handler: handler, Exact: exact},
  47. )
  48. }
  49. func (r *Router) GET(prefix string, handler RouteHandler, exact bool) {
  50. r.Add(http.MethodGet, prefix, handler, exact)
  51. }
  52. func (r *Router) OPTIONS(prefix string, handler RouteHandler, exact bool) {
  53. r.Add(http.MethodOptions, prefix, handler, exact)
  54. }
  55. func (r *Router) HEAD(prefix string, handler RouteHandler, exact bool) {
  56. r.Add(http.MethodHead, prefix, handler, exact)
  57. }
  58. func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
  59. req = setRequestTime(req)
  60. reqID := req.Header.Get(xRequestIDHeader)
  61. if len(reqID) == 0 || !requestIDRe.MatchString(reqID) {
  62. reqID, _ = nanoid.New()
  63. }
  64. rw.Header().Set("Server", "imgproxy")
  65. rw.Header().Set(xRequestIDHeader, reqID)
  66. defer func() {
  67. if rerr := recover(); rerr != nil {
  68. if err, ok := rerr.(error); ok && r.PanicHandler != nil {
  69. r.PanicHandler(reqID, rw, req, err)
  70. } else {
  71. panic(rerr)
  72. }
  73. }
  74. }()
  75. LogRequest(reqID, req)
  76. for _, rr := range r.Routes {
  77. if rr.isMatch(req) {
  78. rr.Handler(reqID, rw, req)
  79. return
  80. }
  81. }
  82. log.Warningf("Route for %s is not defined", req.URL.Path)
  83. rw.WriteHeader(404)
  84. }