router.go 6.9 KB

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