router.go 7.1 KB

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