router.go 2.1 KB

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