router.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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. if !rr.silent {
  105. LogRequest(reqID, req)
  106. }
  107. rr.handler(reqID, rw, req)
  108. return
  109. }
  110. }
  111. // Means that we have not found matching route
  112. LogRequest(reqID, req)
  113. LogResponse(reqID, req, http.StatusNotFound, newRouteNotDefinedError(req.URL.Path))
  114. r.NotFoundHandler(reqID, rw, req)
  115. }
  116. // NotFoundHandler is default 404 handler
  117. func (r *Router) NotFoundHandler(reqID string, rw http.ResponseWriter, req *http.Request) error {
  118. rw.Header().Set(httpheaders.ContentType, "text/plain")
  119. rw.WriteHeader(http.StatusNotFound)
  120. rw.Write([]byte{' '}) // Write a single byte to make AWS Lambda happy
  121. return nil
  122. }
  123. // OkHandler is a default 200 OK handler
  124. func (r *Router) OkHandler(reqID string, rw http.ResponseWriter, req *http.Request) error {
  125. rw.Header().Set(httpheaders.ContentType, "text/plain")
  126. rw.WriteHeader(http.StatusOK)
  127. rw.Write([]byte{' '}) // Write a single byte to make AWS Lambda happy
  128. return nil
  129. }
  130. // getRequestID tries to read request id from headers or from lambda
  131. // context or generates a new one if nothing found.
  132. func (r *Router) getRequestID(req *http.Request) string {
  133. // Get request ID from headers (if any)
  134. reqID := req.Header.Get(httpheaders.XRequestID)
  135. if len(reqID) == 0 || !requestIDRe.MatchString(reqID) {
  136. lambdaContextVal := req.Header.Get(httpheaders.XAmznRequestContextHeader)
  137. if len(lambdaContextVal) > 0 {
  138. var lambdaContext struct {
  139. RequestID string `json:"requestId"`
  140. }
  141. err := json.Unmarshal([]byte(lambdaContextVal), &lambdaContext)
  142. if err == nil && len(lambdaContext.RequestID) > 0 {
  143. reqID = lambdaContext.RequestID
  144. }
  145. }
  146. }
  147. if len(reqID) == 0 || !requestIDRe.MatchString(reqID) {
  148. reqID, _ = nanoid.New()
  149. }
  150. return reqID
  151. }
  152. // replaceRemoteAddr rewrites the req.RemoteAddr property from request headers
  153. func (r *Router) replaceRemoteAddr(req *http.Request) {
  154. cfConnectingIP := req.Header.Get(httpheaders.CFConnectingIP)
  155. xForwardedFor := req.Header.Get(httpheaders.XForwardedFor)
  156. xRealIP := req.Header.Get(httpheaders.XRealIP)
  157. switch {
  158. case len(cfConnectingIP) > 0:
  159. replaceRemoteAddr(req, cfConnectingIP)
  160. case len(xForwardedFor) > 0:
  161. if index := strings.Index(xForwardedFor, ","); index > 0 {
  162. xForwardedFor = xForwardedFor[:index]
  163. }
  164. replaceRemoteAddr(req, xForwardedFor)
  165. case len(xRealIP) > 0:
  166. replaceRemoteAddr(req, xRealIP)
  167. }
  168. }
  169. // replaceRemoteAddr sets the req.RemoteAddr for request
  170. func replaceRemoteAddr(req *http.Request, ip string) {
  171. _, port, err := net.SplitHostPort(req.RemoteAddr)
  172. if err != nil {
  173. port = "80"
  174. }
  175. req.RemoteAddr = net.JoinHostPort(strings.TrimSpace(ip), port)
  176. }
  177. // isMatch checks that a request matches route
  178. func (r *route) isMatch(req *http.Request) bool {
  179. methodMatches := r.method == req.Method
  180. notExactPathMathes := !r.exact && strings.HasPrefix(req.URL.Path, r.path)
  181. exactPathMatches := r.exact && req.URL.Path == r.path
  182. return methodMatches && (notExactPathMathes || exactPathMatches)
  183. }
  184. // Silent sets Silent flag which supresses logs to true. We do not need to log
  185. // requests like /health of /favicon.ico
  186. func (r *route) Silent() *route {
  187. r.silent = true
  188. return r
  189. }