router.go 6.5 KB

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