router.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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) HEAD(prefix string, handler routeHandler, exact bool) {
  53. r.Add(http.MethodHead, prefix, handler, exact)
  54. }
  55. func (r *router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
  56. req = req.WithContext(setTimerSince(req.Context()))
  57. reqID := req.Header.Get(xRequestIDHeader)
  58. if len(reqID) == 0 || !requestIDRe.MatchString(reqID) {
  59. reqID, _ = nanoid.Nanoid()
  60. }
  61. rw.Header().Set("Server", "imgproxy")
  62. rw.Header().Set(xRequestIDHeader, reqID)
  63. defer func() {
  64. if rerr := recover(); rerr != nil {
  65. if err, ok := rerr.(error); ok && r.PanicHandler != nil {
  66. r.PanicHandler(reqID, rw, req, err)
  67. } else {
  68. panic(rerr)
  69. }
  70. }
  71. }()
  72. logRequest(reqID, req)
  73. for _, rr := range r.Routes {
  74. if rr.IsMatch(req) {
  75. rr.Handler(reqID, rw, req)
  76. return
  77. }
  78. }
  79. logWarning("Route for %s is not defined", req.URL.Path)
  80. rw.WriteHeader(404)
  81. }