1
0

router.go 6.4 KB

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