router.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. package server
  2. import (
  3. "encoding/json"
  4. "net"
  5. "net/http"
  6. "regexp"
  7. "slices"
  8. "strings"
  9. nanoid "github.com/matoous/go-nanoid/v2"
  10. "github.com/imgproxy/imgproxy/v3/httpheaders"
  11. "github.com/imgproxy/imgproxy/v3/server/responsewriter"
  12. )
  13. const (
  14. // defaultServerName is the default name of the server
  15. defaultServerName = "imgproxy"
  16. )
  17. var (
  18. // requestIDRe is a regular expression for validating request IDs
  19. requestIDRe = regexp.MustCompile(`^[A-Za-z0-9_\-]+$`)
  20. )
  21. type ResponseWriter = *responsewriter.Writer
  22. // RouteHandler is a function that handles HTTP requests.
  23. type RouteHandler func(string, ResponseWriter, *http.Request) error
  24. // Middleware is a function that wraps a RouteHandler with additional functionality.
  25. type Middleware func(next RouteHandler) RouteHandler
  26. // route represents a single route in the router.
  27. type route struct {
  28. method string // method is the HTTP method for a route
  29. path string // path represents a route path
  30. exact bool // exact means that path must match exactly, otherwise any prefixed matches
  31. handler RouteHandler // handler is the function that handles the route
  32. silent bool // Silent route (no logs)
  33. }
  34. // Router is responsible for routing HTTP requests
  35. type Router struct {
  36. // Response writers factory
  37. rwFactory *responsewriter.Factory
  38. // config represents the server configuration
  39. config *Config
  40. // routes is the collection of all routes
  41. routes []*route
  42. }
  43. // NewRouter creates a new Router instance
  44. func NewRouter(config *Config) (*Router, error) {
  45. if err := config.Validate(); err != nil {
  46. return nil, err
  47. }
  48. rwf, err := responsewriter.NewFactory(&config.ResponseWriter)
  49. if err != nil {
  50. return nil, err
  51. }
  52. return &Router{
  53. rwFactory: rwf,
  54. config: config,
  55. }, nil
  56. }
  57. // add adds an abitary route to the router
  58. func (r *Router) add(method, path string, handler RouteHandler, middlewares ...Middleware) *route {
  59. for _, m := range middlewares {
  60. handler = m(handler)
  61. }
  62. exact := true
  63. if strings.HasSuffix(path, "*") {
  64. exact = false
  65. path = strings.TrimSuffix(path, "*")
  66. }
  67. newRoute := &route{
  68. method: method,
  69. path: r.config.PathPrefix + path,
  70. handler: handler,
  71. exact: exact,
  72. }
  73. r.routes = append(r.routes, newRoute)
  74. // Sort routes by exact flag, exact routes go first in the
  75. // same order they were added
  76. slices.SortStableFunc(r.routes, func(a, b *route) int {
  77. switch {
  78. case a.exact == b.exact:
  79. return 0
  80. case a.exact:
  81. return -1
  82. default:
  83. return 1
  84. }
  85. })
  86. return newRoute
  87. }
  88. // GET adds GET route
  89. func (r *Router) GET(path string, handler RouteHandler, middlewares ...Middleware) *route {
  90. return r.add(http.MethodGet, path, handler, middlewares...)
  91. }
  92. // OPTIONS adds OPTIONS route
  93. func (r *Router) OPTIONS(path string, handler RouteHandler, middlewares ...Middleware) *route {
  94. return r.add(http.MethodOptions, path, handler, middlewares...)
  95. }
  96. // HEAD adds HEAD route
  97. func (r *Router) HEAD(path string, handler RouteHandler, middlewares ...Middleware) *route {
  98. return r.add(http.MethodHead, path, handler, middlewares...)
  99. }
  100. // ServeHTTP serves routes
  101. func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
  102. // Attach timer to the context
  103. req, timeoutCancel := startRequestTimer(req)
  104. defer timeoutCancel()
  105. // Create the [ResponseWriter]
  106. rww := r.rwFactory.NewWriter(rw)
  107. // Get/create request ID
  108. reqID := r.getRequestID(req)
  109. // Replace request IP from headers
  110. r.replaceRemoteAddr(req)
  111. rww.Header().Set(httpheaders.Server, defaultServerName)
  112. rww.Header().Set(httpheaders.XRequestID, reqID)
  113. for _, rr := range r.routes {
  114. if !rr.isMatch(req) {
  115. continue
  116. }
  117. // Set req.Pattern. We use it to trim path prefixes in handlers.
  118. req.Pattern = rr.path
  119. if !rr.silent {
  120. LogRequest(reqID, req)
  121. }
  122. rr.handler(reqID, rww, req)
  123. return
  124. }
  125. // Means that we have not found matching route
  126. LogRequest(reqID, req)
  127. LogResponse(reqID, req, http.StatusNotFound, newRouteNotDefinedError(req.URL.Path))
  128. r.NotFoundHandler(reqID, rww, req)
  129. }
  130. // NotFoundHandler is default 404 handler
  131. func (r *Router) NotFoundHandler(reqID string, rw ResponseWriter, req *http.Request) error {
  132. rw.Header().Set(httpheaders.ContentType, "text/plain")
  133. rw.WriteHeader(http.StatusNotFound)
  134. rw.Write([]byte{' '}) // Write a single byte to make AWS Lambda happy
  135. return nil
  136. }
  137. // OkHandler is a default 200 OK handler
  138. func (r *Router) OkHandler(reqID string, rw ResponseWriter, req *http.Request) error {
  139. rw.Header().Set(httpheaders.ContentType, "text/plain")
  140. rw.WriteHeader(http.StatusOK)
  141. rw.Write([]byte{' '}) // Write a single byte to make AWS Lambda happy
  142. return nil
  143. }
  144. // getRequestID tries to read request id from headers or from lambda
  145. // context or generates a new one if nothing found.
  146. func (r *Router) getRequestID(req *http.Request) string {
  147. // Get request ID from headers (if any)
  148. reqID := req.Header.Get(httpheaders.XRequestID)
  149. if len(reqID) == 0 || !requestIDRe.MatchString(reqID) {
  150. lambdaContextVal := req.Header.Get(httpheaders.XAmznRequestContextHeader)
  151. if len(lambdaContextVal) > 0 {
  152. var lambdaContext struct {
  153. RequestID string `json:"requestId"`
  154. }
  155. err := json.Unmarshal([]byte(lambdaContextVal), &lambdaContext)
  156. if err == nil && len(lambdaContext.RequestID) > 0 {
  157. reqID = lambdaContext.RequestID
  158. }
  159. }
  160. }
  161. if len(reqID) == 0 || !requestIDRe.MatchString(reqID) {
  162. reqID, _ = nanoid.New()
  163. }
  164. return reqID
  165. }
  166. // replaceRemoteAddr rewrites the req.RemoteAddr property from request headers
  167. func (r *Router) replaceRemoteAddr(req *http.Request) {
  168. cfConnectingIP := req.Header.Get(httpheaders.CFConnectingIP)
  169. xForwardedFor := req.Header.Get(httpheaders.XForwardedFor)
  170. xRealIP := req.Header.Get(httpheaders.XRealIP)
  171. switch {
  172. case len(cfConnectingIP) > 0:
  173. replaceRemoteAddr(req, cfConnectingIP)
  174. case len(xForwardedFor) > 0:
  175. if index := strings.Index(xForwardedFor, ","); index > 0 {
  176. xForwardedFor = xForwardedFor[:index]
  177. }
  178. replaceRemoteAddr(req, xForwardedFor)
  179. case len(xRealIP) > 0:
  180. replaceRemoteAddr(req, xRealIP)
  181. }
  182. }
  183. // replaceRemoteAddr sets the req.RemoteAddr for request
  184. func replaceRemoteAddr(req *http.Request, ip string) {
  185. _, port, err := net.SplitHostPort(req.RemoteAddr)
  186. if err != nil {
  187. port = "80"
  188. }
  189. req.RemoteAddr = net.JoinHostPort(strings.TrimSpace(ip), port)
  190. }
  191. // isMatch checks that a request matches route
  192. func (r *route) isMatch(req *http.Request) bool {
  193. methodMatches := r.method == req.Method
  194. notExactPathMathes := !r.exact && strings.HasPrefix(req.URL.Path, r.path)
  195. exactPathMatches := r.exact && req.URL.Path == r.path
  196. return methodMatches && (notExactPathMathes || exactPathMatches)
  197. }
  198. // Silent sets Silent flag which supresses logs to true. We do not need to log
  199. // requests like /health of /favicon.ico
  200. func (r *route) Silent() *route {
  201. r.silent = true
  202. return r
  203. }