router.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package main
  2. import (
  3. "net/http"
  4. "regexp"
  5. "strings"
  6. nanoid "github.com/matoous/go-nanoid"
  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. Routes []*route
  24. PanicHandler panicHandler
  25. }
  26. func (r *route) IsMatch(req *http.Request) bool {
  27. if r.Method != req.Method {
  28. return false
  29. }
  30. if r.Exact {
  31. return req.URL.Path == r.Prefix
  32. }
  33. return strings.HasPrefix(req.URL.Path, r.Prefix)
  34. }
  35. func newRouter() *router {
  36. return &router{
  37. Routes: make([]*route, 0),
  38. }
  39. }
  40. func (r *router) Add(method, prefix string, handler routeHandler, exact bool) {
  41. r.Routes = append(
  42. r.Routes,
  43. &route{Method: method, Prefix: prefix, Handler: handler, Exact: exact},
  44. )
  45. }
  46. func (r *router) GET(prefix string, handler routeHandler, exact bool) {
  47. r.Add(http.MethodGet, prefix, handler, exact)
  48. }
  49. func (r *router) OPTIONS(prefix string, handler routeHandler, exact bool) {
  50. r.Add(http.MethodOptions, prefix, handler, exact)
  51. }
  52. func (r *router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
  53. req = req.WithContext(setTimerSince(req.Context()))
  54. reqID := req.Header.Get(xRequestIDHeader)
  55. if len(reqID) == 0 || !requestIDRe.MatchString(reqID) {
  56. reqID, _ = nanoid.Nanoid()
  57. }
  58. rw.Header().Set("Server", "imgproxy")
  59. rw.Header().Set(xRequestIDHeader, reqID)
  60. defer func() {
  61. if rerr := recover(); rerr != nil {
  62. if err, ok := rerr.(error); ok && r.PanicHandler != nil {
  63. r.PanicHandler(reqID, rw, req, err)
  64. } else {
  65. panic(rerr)
  66. }
  67. }
  68. }()
  69. logRequest(reqID, req)
  70. for _, rr := range r.Routes {
  71. if rr.IsMatch(req) {
  72. rr.Handler(reqID, rw, req)
  73. return
  74. }
  75. }
  76. logWarning("Route for %s is not defined", req.URL.Path)
  77. rw.WriteHeader(404)
  78. }