gin.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. // Copyright 2014 Manu Martinez-Almeida. All rights reserved.
  2. // Use of this source code is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package gin
  5. import (
  6. "fmt"
  7. "html/template"
  8. "net"
  9. "net/http"
  10. "os"
  11. "path"
  12. "regexp"
  13. "strings"
  14. "sync"
  15. "github.com/gin-gonic/gin/internal/bytesconv"
  16. "github.com/gin-gonic/gin/render"
  17. "golang.org/x/net/http2"
  18. "golang.org/x/net/http2/h2c"
  19. )
  20. const defaultMultipartMemory = 32 << 20 // 32 MB
  21. var (
  22. default404Body = []byte("404 page not found")
  23. default405Body = []byte("405 method not allowed")
  24. )
  25. var defaultPlatform string
  26. var defaultTrustedCIDRs = []*net.IPNet{
  27. { // 0.0.0.0/0 (IPv4)
  28. IP: net.IP{0x0, 0x0, 0x0, 0x0},
  29. Mask: net.IPMask{0x0, 0x0, 0x0, 0x0},
  30. },
  31. { // ::/0 (IPv6)
  32. IP: net.IP{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
  33. Mask: net.IPMask{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
  34. },
  35. }
  36. var regSafePrefix = regexp.MustCompile("[^a-zA-Z0-9/-]+")
  37. var regRemoveRepeatedChar = regexp.MustCompile("/{2,}")
  38. // HandlerFunc defines the handler used by gin middleware as return value.
  39. type HandlerFunc func(*Context)
  40. // HandlersChain defines a HandlerFunc slice.
  41. type HandlersChain []HandlerFunc
  42. // Last returns the last handler in the chain. i.e. the last handler is the main one.
  43. func (c HandlersChain) Last() HandlerFunc {
  44. if length := len(c); length > 0 {
  45. return c[length-1]
  46. }
  47. return nil
  48. }
  49. // RouteInfo represents a request route's specification which contains method and path and its handler.
  50. type RouteInfo struct {
  51. Method string
  52. Path string
  53. Handler string
  54. HandlerFunc HandlerFunc
  55. }
  56. // RoutesInfo defines a RouteInfo slice.
  57. type RoutesInfo []RouteInfo
  58. // Trusted platforms
  59. const (
  60. // PlatformGoogleAppEngine when running on Google App Engine. Trust X-Appengine-Remote-Addr
  61. // for determining the client's IP
  62. PlatformGoogleAppEngine = "X-Appengine-Remote-Addr"
  63. // PlatformCloudflare when using Cloudflare's CDN. Trust CF-Connecting-IP for determining
  64. // the client's IP
  65. PlatformCloudflare = "CF-Connecting-IP"
  66. )
  67. // Engine is the framework's instance, it contains the muxer, middleware and configuration settings.
  68. // Create an instance of Engine, by using New() or Default()
  69. type Engine struct {
  70. RouterGroup
  71. // RedirectTrailingSlash enables automatic redirection if the current route can't be matched but a
  72. // handler for the path with (without) the trailing slash exists.
  73. // For example if /foo/ is requested but a route only exists for /foo, the
  74. // client is redirected to /foo with http status code 301 for GET requests
  75. // and 307 for all other request methods.
  76. RedirectTrailingSlash bool
  77. // RedirectFixedPath if enabled, the router tries to fix the current request path, if no
  78. // handle is registered for it.
  79. // First superfluous path elements like ../ or // are removed.
  80. // Afterwards the router does a case-insensitive lookup of the cleaned path.
  81. // If a handle can be found for this route, the router makes a redirection
  82. // to the corrected path with status code 301 for GET requests and 307 for
  83. // all other request methods.
  84. // For example /FOO and /..//Foo could be redirected to /foo.
  85. // RedirectTrailingSlash is independent of this option.
  86. RedirectFixedPath bool
  87. // HandleMethodNotAllowed if enabled, the router checks if another method is allowed for the
  88. // current route, if the current request can not be routed.
  89. // If this is the case, the request is answered with 'Method Not Allowed'
  90. // and HTTP status code 405.
  91. // If no other Method is allowed, the request is delegated to the NotFound
  92. // handler.
  93. HandleMethodNotAllowed bool
  94. // ForwardedByClientIP if enabled, client IP will be parsed from the request's headers that
  95. // match those stored at `(*gin.Engine).RemoteIPHeaders`. If no IP was
  96. // fetched, it falls back to the IP obtained from
  97. // `(*gin.Context).Request.RemoteAddr`.
  98. ForwardedByClientIP bool
  99. // AppEngine was deprecated.
  100. // Deprecated: USE `TrustedPlatform` WITH VALUE `gin.PlatformGoogleAppEngine` INSTEAD
  101. // #726 #755 If enabled, it will trust some headers starting with
  102. // 'X-AppEngine...' for better integration with that PaaS.
  103. AppEngine bool
  104. // UseRawPath if enabled, the url.RawPath will be used to find parameters.
  105. UseRawPath bool
  106. // UnescapePathValues if true, the path value will be unescaped.
  107. // If UseRawPath is false (by default), the UnescapePathValues effectively is true,
  108. // as url.Path gonna be used, which is already unescaped.
  109. UnescapePathValues bool
  110. // RemoveExtraSlash a parameter can be parsed from the URL even with extra slashes.
  111. // See the PR #1817 and issue #1644
  112. RemoveExtraSlash bool
  113. // RemoteIPHeaders list of headers used to obtain the client IP when
  114. // `(*gin.Engine).ForwardedByClientIP` is `true` and
  115. // `(*gin.Context).Request.RemoteAddr` is matched by at least one of the
  116. // network origins of list defined by `(*gin.Engine).SetTrustedProxies()`.
  117. RemoteIPHeaders []string
  118. // TrustedPlatform if set to a constant of value gin.Platform*, trusts the headers set by
  119. // that platform, for example to determine the client IP
  120. TrustedPlatform string
  121. // MaxMultipartMemory value of 'maxMemory' param that is given to http.Request's ParseMultipartForm
  122. // method call.
  123. MaxMultipartMemory int64
  124. // UseH2C enable h2c support.
  125. UseH2C bool
  126. // ContextWithFallback enable fallback Context.Deadline(), Context.Done(), Context.Err() and Context.Value() when Context.Request.Context() is not nil.
  127. ContextWithFallback bool
  128. delims render.Delims
  129. secureJSONPrefix string
  130. HTMLRender render.HTMLRender
  131. FuncMap template.FuncMap
  132. allNoRoute HandlersChain
  133. allNoMethod HandlersChain
  134. noRoute HandlersChain
  135. noMethod HandlersChain
  136. pool sync.Pool
  137. trees methodTrees
  138. maxParams uint16
  139. maxSections uint16
  140. trustedProxies []string
  141. trustedCIDRs []*net.IPNet
  142. }
  143. var _ IRouter = (*Engine)(nil)
  144. // New returns a new blank Engine instance without any middleware attached.
  145. // By default, the configuration is:
  146. // - RedirectTrailingSlash: true
  147. // - RedirectFixedPath: false
  148. // - HandleMethodNotAllowed: false
  149. // - ForwardedByClientIP: true
  150. // - UseRawPath: false
  151. // - UnescapePathValues: true
  152. func New() *Engine {
  153. debugPrintWARNINGNew()
  154. engine := &Engine{
  155. RouterGroup: RouterGroup{
  156. Handlers: nil,
  157. basePath: "/",
  158. root: true,
  159. },
  160. FuncMap: template.FuncMap{},
  161. RedirectTrailingSlash: true,
  162. RedirectFixedPath: false,
  163. HandleMethodNotAllowed: false,
  164. ForwardedByClientIP: true,
  165. RemoteIPHeaders: []string{"X-Forwarded-For", "X-Real-IP"},
  166. TrustedPlatform: defaultPlatform,
  167. UseRawPath: false,
  168. RemoveExtraSlash: false,
  169. UnescapePathValues: true,
  170. MaxMultipartMemory: defaultMultipartMemory,
  171. trees: make(methodTrees, 0, 9),
  172. delims: render.Delims{Left: "{{", Right: "}}"},
  173. secureJSONPrefix: "while(1);",
  174. trustedProxies: []string{"0.0.0.0/0", "::/0"},
  175. trustedCIDRs: defaultTrustedCIDRs,
  176. }
  177. engine.RouterGroup.engine = engine
  178. engine.pool.New = func() any {
  179. return engine.allocateContext(engine.maxParams)
  180. }
  181. return engine
  182. }
  183. // Default returns an Engine instance with the Logger and Recovery middleware already attached.
  184. func Default() *Engine {
  185. debugPrintWARNINGDefault()
  186. engine := New()
  187. engine.Use(Logger(), Recovery())
  188. return engine
  189. }
  190. func (engine *Engine) Handler() http.Handler {
  191. if !engine.UseH2C {
  192. return engine
  193. }
  194. h2s := &http2.Server{}
  195. return h2c.NewHandler(engine, h2s)
  196. }
  197. func (engine *Engine) allocateContext(maxParams uint16) *Context {
  198. v := make(Params, 0, maxParams)
  199. skippedNodes := make([]skippedNode, 0, engine.maxSections)
  200. return &Context{engine: engine, params: &v, skippedNodes: &skippedNodes}
  201. }
  202. // Delims sets template left and right delims and returns an Engine instance.
  203. func (engine *Engine) Delims(left, right string) *Engine {
  204. engine.delims = render.Delims{Left: left, Right: right}
  205. return engine
  206. }
  207. // SecureJsonPrefix sets the secureJSONPrefix used in Context.SecureJSON.
  208. func (engine *Engine) SecureJsonPrefix(prefix string) *Engine {
  209. engine.secureJSONPrefix = prefix
  210. return engine
  211. }
  212. // LoadHTMLGlob loads HTML files identified by glob pattern
  213. // and associates the result with HTML renderer.
  214. func (engine *Engine) LoadHTMLGlob(pattern string) {
  215. left := engine.delims.Left
  216. right := engine.delims.Right
  217. templ := template.Must(template.New("").Delims(left, right).Funcs(engine.FuncMap).ParseGlob(pattern))
  218. if IsDebugging() {
  219. debugPrintLoadTemplate(templ)
  220. engine.HTMLRender = render.HTMLDebug{Glob: pattern, FuncMap: engine.FuncMap, Delims: engine.delims}
  221. return
  222. }
  223. engine.SetHTMLTemplate(templ)
  224. }
  225. // LoadHTMLFiles loads a slice of HTML files
  226. // and associates the result with HTML renderer.
  227. func (engine *Engine) LoadHTMLFiles(files ...string) {
  228. if IsDebugging() {
  229. engine.HTMLRender = render.HTMLDebug{Files: files, FuncMap: engine.FuncMap, Delims: engine.delims}
  230. return
  231. }
  232. templ := template.Must(template.New("").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap).ParseFiles(files...))
  233. engine.SetHTMLTemplate(templ)
  234. }
  235. // SetHTMLTemplate associate a template with HTML renderer.
  236. func (engine *Engine) SetHTMLTemplate(templ *template.Template) {
  237. if len(engine.trees) > 0 {
  238. debugPrintWARNINGSetHTMLTemplate()
  239. }
  240. engine.HTMLRender = render.HTMLProduction{Template: templ.Funcs(engine.FuncMap)}
  241. }
  242. // SetFuncMap sets the FuncMap used for template.FuncMap.
  243. func (engine *Engine) SetFuncMap(funcMap template.FuncMap) {
  244. engine.FuncMap = funcMap
  245. }
  246. // NoRoute adds handlers for NoRoute. It returns a 404 code by default.
  247. func (engine *Engine) NoRoute(handlers ...HandlerFunc) {
  248. engine.noRoute = handlers
  249. engine.rebuild404Handlers()
  250. }
  251. // NoMethod sets the handlers called when Engine.HandleMethodNotAllowed = true.
  252. func (engine *Engine) NoMethod(handlers ...HandlerFunc) {
  253. engine.noMethod = handlers
  254. engine.rebuild405Handlers()
  255. }
  256. // Use attaches a global middleware to the router. i.e. the middleware attached through Use() will be
  257. // included in the handlers chain for every single request. Even 404, 405, static files...
  258. // For example, this is the right place for a logger or error management middleware.
  259. func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes {
  260. engine.RouterGroup.Use(middleware...)
  261. engine.rebuild404Handlers()
  262. engine.rebuild405Handlers()
  263. return engine
  264. }
  265. func (engine *Engine) rebuild404Handlers() {
  266. engine.allNoRoute = engine.combineHandlers(engine.noRoute)
  267. }
  268. func (engine *Engine) rebuild405Handlers() {
  269. engine.allNoMethod = engine.combineHandlers(engine.noMethod)
  270. }
  271. func (engine *Engine) addRoute(method, path string, handlers HandlersChain) {
  272. assert1(path[0] == '/', "path must begin with '/'")
  273. assert1(method != "", "HTTP method can not be empty")
  274. assert1(len(handlers) > 0, "there must be at least one handler")
  275. debugPrintRoute(method, path, handlers)
  276. root := engine.trees.get(method)
  277. if root == nil {
  278. root = new(node)
  279. root.fullPath = "/"
  280. engine.trees = append(engine.trees, methodTree{method: method, root: root})
  281. }
  282. root.addRoute(path, handlers)
  283. // Update maxParams
  284. if paramsCount := countParams(path); paramsCount > engine.maxParams {
  285. engine.maxParams = paramsCount
  286. }
  287. if sectionsCount := countSections(path); sectionsCount > engine.maxSections {
  288. engine.maxSections = sectionsCount
  289. }
  290. }
  291. // Routes returns a slice of registered routes, including some useful information, such as:
  292. // the http method, path and the handler name.
  293. func (engine *Engine) Routes() (routes RoutesInfo) {
  294. for _, tree := range engine.trees {
  295. routes = iterate("", tree.method, routes, tree.root)
  296. }
  297. return routes
  298. }
  299. func iterate(path, method string, routes RoutesInfo, root *node) RoutesInfo {
  300. path += root.path
  301. if len(root.handlers) > 0 {
  302. handlerFunc := root.handlers.Last()
  303. routes = append(routes, RouteInfo{
  304. Method: method,
  305. Path: path,
  306. Handler: nameOfFunction(handlerFunc),
  307. HandlerFunc: handlerFunc,
  308. })
  309. }
  310. for _, child := range root.children {
  311. routes = iterate(path, method, routes, child)
  312. }
  313. return routes
  314. }
  315. // Run attaches the router to a http.Server and starts listening and serving HTTP requests.
  316. // It is a shortcut for http.ListenAndServe(addr, router)
  317. // Note: this method will block the calling goroutine indefinitely unless an error happens.
  318. func (engine *Engine) Run(addr ...string) (err error) {
  319. defer func() { debugPrintError(err) }()
  320. if engine.isUnsafeTrustedProxies() {
  321. debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" +
  322. "Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.")
  323. }
  324. address := resolveAddress(addr)
  325. debugPrint("Listening and serving HTTP on %s\n", address)
  326. err = http.ListenAndServe(address, engine.Handler())
  327. return
  328. }
  329. func (engine *Engine) prepareTrustedCIDRs() ([]*net.IPNet, error) {
  330. if engine.trustedProxies == nil {
  331. return nil, nil
  332. }
  333. cidr := make([]*net.IPNet, 0, len(engine.trustedProxies))
  334. for _, trustedProxy := range engine.trustedProxies {
  335. if !strings.Contains(trustedProxy, "/") {
  336. ip := parseIP(trustedProxy)
  337. if ip == nil {
  338. return cidr, &net.ParseError{Type: "IP address", Text: trustedProxy}
  339. }
  340. switch len(ip) {
  341. case net.IPv4len:
  342. trustedProxy += "/32"
  343. case net.IPv6len:
  344. trustedProxy += "/128"
  345. }
  346. }
  347. _, cidrNet, err := net.ParseCIDR(trustedProxy)
  348. if err != nil {
  349. return cidr, err
  350. }
  351. cidr = append(cidr, cidrNet)
  352. }
  353. return cidr, nil
  354. }
  355. // SetTrustedProxies set a list of network origins (IPv4 addresses,
  356. // IPv4 CIDRs, IPv6 addresses or IPv6 CIDRs) from which to trust
  357. // request's headers that contain alternative client IP when
  358. // `(*gin.Engine).ForwardedByClientIP` is `true`. `TrustedProxies`
  359. // feature is enabled by default, and it also trusts all proxies
  360. // by default. If you want to disable this feature, use
  361. // Engine.SetTrustedProxies(nil), then Context.ClientIP() will
  362. // return the remote address directly.
  363. func (engine *Engine) SetTrustedProxies(trustedProxies []string) error {
  364. engine.trustedProxies = trustedProxies
  365. return engine.parseTrustedProxies()
  366. }
  367. // isUnsafeTrustedProxies checks if Engine.trustedCIDRs contains all IPs, it's not safe if it has (returns true)
  368. func (engine *Engine) isUnsafeTrustedProxies() bool {
  369. return engine.isTrustedProxy(net.ParseIP("0.0.0.0")) || engine.isTrustedProxy(net.ParseIP("::"))
  370. }
  371. // parseTrustedProxies parse Engine.trustedProxies to Engine.trustedCIDRs
  372. func (engine *Engine) parseTrustedProxies() error {
  373. trustedCIDRs, err := engine.prepareTrustedCIDRs()
  374. engine.trustedCIDRs = trustedCIDRs
  375. return err
  376. }
  377. // isTrustedProxy will check whether the IP address is included in the trusted list according to Engine.trustedCIDRs
  378. func (engine *Engine) isTrustedProxy(ip net.IP) bool {
  379. if engine.trustedCIDRs == nil {
  380. return false
  381. }
  382. for _, cidr := range engine.trustedCIDRs {
  383. if cidr.Contains(ip) {
  384. return true
  385. }
  386. }
  387. return false
  388. }
  389. // validateHeader will parse X-Forwarded-For header and return the trusted client IP address
  390. func (engine *Engine) validateHeader(header string) (clientIP string, valid bool) {
  391. if header == "" {
  392. return "", false
  393. }
  394. items := strings.Split(header, ",")
  395. for i := len(items) - 1; i >= 0; i-- {
  396. ipStr := strings.TrimSpace(items[i])
  397. ip := net.ParseIP(ipStr)
  398. if ip == nil {
  399. break
  400. }
  401. // X-Forwarded-For is appended by proxy
  402. // Check IPs in reverse order and stop when find untrusted proxy
  403. if (i == 0) || (!engine.isTrustedProxy(ip)) {
  404. return ipStr, true
  405. }
  406. }
  407. return "", false
  408. }
  409. // parseIP parse a string representation of an IP and returns a net.IP with the
  410. // minimum byte representation or nil if input is invalid.
  411. func parseIP(ip string) net.IP {
  412. parsedIP := net.ParseIP(ip)
  413. if ipv4 := parsedIP.To4(); ipv4 != nil {
  414. // return ip in a 4-byte representation
  415. return ipv4
  416. }
  417. // return ip in a 16-byte representation or nil
  418. return parsedIP
  419. }
  420. // RunTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests.
  421. // It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router)
  422. // Note: this method will block the calling goroutine indefinitely unless an error happens.
  423. func (engine *Engine) RunTLS(addr, certFile, keyFile string) (err error) {
  424. debugPrint("Listening and serving HTTPS on %s\n", addr)
  425. defer func() { debugPrintError(err) }()
  426. if engine.isUnsafeTrustedProxies() {
  427. debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" +
  428. "Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.")
  429. }
  430. err = http.ListenAndServeTLS(addr, certFile, keyFile, engine.Handler())
  431. return
  432. }
  433. // RunUnix attaches the router to a http.Server and starts listening and serving HTTP requests
  434. // through the specified unix socket (i.e. a file).
  435. // Note: this method will block the calling goroutine indefinitely unless an error happens.
  436. func (engine *Engine) RunUnix(file string) (err error) {
  437. debugPrint("Listening and serving HTTP on unix:/%s", file)
  438. defer func() { debugPrintError(err) }()
  439. if engine.isUnsafeTrustedProxies() {
  440. debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" +
  441. "Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.")
  442. }
  443. listener, err := net.Listen("unix", file)
  444. if err != nil {
  445. return
  446. }
  447. defer listener.Close()
  448. defer os.Remove(file)
  449. err = http.Serve(listener, engine.Handler())
  450. return
  451. }
  452. // RunFd attaches the router to a http.Server and starts listening and serving HTTP requests
  453. // through the specified file descriptor.
  454. // Note: this method will block the calling goroutine indefinitely unless an error happens.
  455. func (engine *Engine) RunFd(fd int) (err error) {
  456. debugPrint("Listening and serving HTTP on fd@%d", fd)
  457. defer func() { debugPrintError(err) }()
  458. if engine.isUnsafeTrustedProxies() {
  459. debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" +
  460. "Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.")
  461. }
  462. f := os.NewFile(uintptr(fd), fmt.Sprintf("fd@%d", fd))
  463. listener, err := net.FileListener(f)
  464. if err != nil {
  465. return
  466. }
  467. defer listener.Close()
  468. err = engine.RunListener(listener)
  469. return
  470. }
  471. // RunListener attaches the router to a http.Server and starts listening and serving HTTP requests
  472. // through the specified net.Listener
  473. func (engine *Engine) RunListener(listener net.Listener) (err error) {
  474. debugPrint("Listening and serving HTTP on listener what's bind with address@%s", listener.Addr())
  475. defer func() { debugPrintError(err) }()
  476. if engine.isUnsafeTrustedProxies() {
  477. debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" +
  478. "Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.")
  479. }
  480. err = http.Serve(listener, engine.Handler())
  481. return
  482. }
  483. // ServeHTTP conforms to the http.Handler interface.
  484. func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  485. c := engine.pool.Get().(*Context)
  486. c.writermem.reset(w)
  487. c.Request = req
  488. c.reset()
  489. engine.handleHTTPRequest(c)
  490. engine.pool.Put(c)
  491. }
  492. // HandleContext re-enters a context that has been rewritten.
  493. // This can be done by setting c.Request.URL.Path to your new target.
  494. // Disclaimer: You can loop yourself to deal with this, use wisely.
  495. func (engine *Engine) HandleContext(c *Context) {
  496. oldIndexValue := c.index
  497. c.reset()
  498. engine.handleHTTPRequest(c)
  499. c.index = oldIndexValue
  500. }
  501. func (engine *Engine) handleHTTPRequest(c *Context) {
  502. httpMethod := c.Request.Method
  503. rPath := c.Request.URL.Path
  504. unescape := false
  505. if engine.UseRawPath && len(c.Request.URL.RawPath) > 0 {
  506. rPath = c.Request.URL.RawPath
  507. unescape = engine.UnescapePathValues
  508. }
  509. if engine.RemoveExtraSlash {
  510. rPath = cleanPath(rPath)
  511. }
  512. // Find root of the tree for the given HTTP method
  513. t := engine.trees
  514. for i, tl := 0, len(t); i < tl; i++ {
  515. if t[i].method != httpMethod {
  516. continue
  517. }
  518. root := t[i].root
  519. // Find route in tree
  520. value := root.getValue(rPath, c.params, c.skippedNodes, unescape)
  521. if value.params != nil {
  522. c.Params = *value.params
  523. }
  524. if value.handlers != nil {
  525. c.handlers = value.handlers
  526. c.fullPath = value.fullPath
  527. c.Next()
  528. c.writermem.WriteHeaderNow()
  529. return
  530. }
  531. if httpMethod != http.MethodConnect && rPath != "/" {
  532. if value.tsr && engine.RedirectTrailingSlash {
  533. redirectTrailingSlash(c)
  534. return
  535. }
  536. if engine.RedirectFixedPath && redirectFixedPath(c, root, engine.RedirectFixedPath) {
  537. return
  538. }
  539. }
  540. break
  541. }
  542. if engine.HandleMethodNotAllowed {
  543. for _, tree := range engine.trees {
  544. if tree.method == httpMethod {
  545. continue
  546. }
  547. if value := tree.root.getValue(rPath, nil, c.skippedNodes, unescape); value.handlers != nil {
  548. c.handlers = engine.allNoMethod
  549. serveError(c, http.StatusMethodNotAllowed, default405Body)
  550. return
  551. }
  552. }
  553. }
  554. c.handlers = engine.allNoRoute
  555. serveError(c, http.StatusNotFound, default404Body)
  556. }
  557. var mimePlain = []string{MIMEPlain}
  558. func serveError(c *Context, code int, defaultMessage []byte) {
  559. c.writermem.status = code
  560. c.Next()
  561. if c.writermem.Written() {
  562. return
  563. }
  564. if c.writermem.Status() == code {
  565. c.writermem.Header()["Content-Type"] = mimePlain
  566. _, err := c.Writer.Write(defaultMessage)
  567. if err != nil {
  568. debugPrint("cannot write message to writer during serve error: %v", err)
  569. }
  570. return
  571. }
  572. c.writermem.WriteHeaderNow()
  573. }
  574. func redirectTrailingSlash(c *Context) {
  575. req := c.Request
  576. p := req.URL.Path
  577. if prefix := path.Clean(c.Request.Header.Get("X-Forwarded-Prefix")); prefix != "." {
  578. prefix = regSafePrefix.ReplaceAllString(prefix, "")
  579. prefix = regRemoveRepeatedChar.ReplaceAllString(prefix, "/")
  580. p = prefix + "/" + req.URL.Path
  581. }
  582. req.URL.Path = p + "/"
  583. if length := len(p); length > 1 && p[length-1] == '/' {
  584. req.URL.Path = p[:length-1]
  585. }
  586. redirectRequest(c)
  587. }
  588. func redirectFixedPath(c *Context, root *node, trailingSlash bool) bool {
  589. req := c.Request
  590. rPath := req.URL.Path
  591. if fixedPath, ok := root.findCaseInsensitivePath(cleanPath(rPath), trailingSlash); ok {
  592. req.URL.Path = bytesconv.BytesToString(fixedPath)
  593. redirectRequest(c)
  594. return true
  595. }
  596. return false
  597. }
  598. func redirectRequest(c *Context) {
  599. req := c.Request
  600. rPath := req.URL.Path
  601. rURL := req.URL.String()
  602. code := http.StatusMovedPermanently // Permanent redirect, request with GET method
  603. if req.Method != http.MethodGet {
  604. code = http.StatusTemporaryRedirect
  605. }
  606. debugPrint("redirecting request %d: %s --> %s", code, rPath, rURL)
  607. http.Redirect(c.Writer, req, rURL, code)
  608. c.writermem.WriteHeaderNow()
  609. }