gin.go
This file
Path
gin.go
861 lines · 28.0 KiB · Go
Last changed by
fix(engine): add default ReadHeaderTimeout to http.Server in Run methods (#4800)Ruben Paribefore adoptiond8f2d58
History of this fileTake it
1// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2// Use of this source code is governed by a MIT style3// license that can be found in the LICENSE file.45package gin67import (8 "fmt"9 "html/template"10 "net"11 "net/http"12 "os"13 "path"14 "strings"15 "sync"16 "time"1718 "github.com/gin-gonic/gin/internal/bytesconv"19 filesystem "github.com/gin-gonic/gin/internal/fs"20 "github.com/gin-gonic/gin/render"21 "github.com/quic-go/quic-go/http3"22 "golang.org/x/net/http2"23 "golang.org/x/net/http2/h2c"24)2526const (27 defaultMultipartMemory = 32 << 20 // 32 MB28 escapedColon = "\\:"29 colon = ":"30 backslash = "\\"31)3233// defaultReadHeaderTimeout is the default ReadHeaderTimeout applied to the34// http.Server created by Run, RunTLS and RunListener. It protects against35// slowloris-style resource exhaustion when the caller does not configure a36// custom http.Server.37const defaultReadHeaderTimeout = 10 * time.Second3839var (40 default404Body = []byte("404 page not found")41 default405Body = []byte("405 method not allowed")42)4344var defaultPlatform string4546var defaultTrustedCIDRs = []*net.IPNet{47 { // 0.0.0.0/0 (IPv4)48 IP: net.IP{0x0, 0x0, 0x0, 0x0},49 Mask: net.IPMask{0x0, 0x0, 0x0, 0x0},50 },51 { // ::/0 (IPv6)52 IP: net.IP{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},53 Mask: net.IPMask{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},54 },55}5657// HandlerFunc defines the handler used by gin middleware as return value.58type HandlerFunc func(*Context)5960// OptionFunc defines the function to change the default configuration61type OptionFunc func(*Engine)6263// HandlersChain defines a HandlerFunc slice.64type HandlersChain []HandlerFunc6566// Last returns the last handler in the chain. i.e. the last handler is the main one.67func (c HandlersChain) Last() HandlerFunc {68 if length := len(c); length > 0 {69 return c[length-1]70 }71 return nil72}7374// RouteInfo represents a request route's specification which contains method and path and its handler.75type RouteInfo struct {76 Method string77 Path string78 Handler string79 HandlerFunc HandlerFunc80}8182// RoutesInfo defines a RouteInfo slice.83type RoutesInfo []RouteInfo8485// Trusted platforms86const (87 // PlatformGoogleAppEngine when running on Google App Engine. Trust X-Appengine-Remote-Addr88 // for determining the client's IP89 PlatformGoogleAppEngine = "X-Appengine-Remote-Addr"90 // PlatformCloudflare when using Cloudflare's CDN. Trust CF-Connecting-IP for determining91 // the client's IP92 PlatformCloudflare = "CF-Connecting-IP"93 // PlatformFlyIO when running on Fly.io. Trust Fly-Client-IP for determining the client's IP94 PlatformFlyIO = "Fly-Client-IP"95)9697// Engine is the framework's instance, it contains the muxer, middleware and configuration settings.98// Create an instance of Engine, by using New() or Default()99type Engine struct {100 RouterGroup101102 // routeTreesUpdated ensures that the initialization or update of the route trees103 // (used for routing HTTP requests) happens only once, even if called multiple times concurrently.104 routeTreesUpdated sync.Once105106 // RedirectTrailingSlash enables automatic redirection if the current route can't be matched but a107 // handler for the path with (without) the trailing slash exists.108 // For example if /foo/ is requested but a route only exists for /foo, the109 // client is redirected to /foo with http status code 301 for GET requests110 // and 307 for all other request methods.111 RedirectTrailingSlash bool112113 // RedirectFixedPath if enabled, the router tries to fix the current request path, if no114 // handle is registered for it.115 // First superfluous path elements like ../ or // are removed.116 // Afterwards the router does a case-insensitive lookup of the cleaned path.117 // If a handle can be found for this route, the router makes a redirection118 // to the corrected path with status code 301 for GET requests and 307 for119 // all other request methods.120 // For example /FOO and /..//Foo could be redirected to /foo.121 // RedirectTrailingSlash is independent of this option.122 RedirectFixedPath bool123124 // HandleMethodNotAllowed if enabled, the router checks if another method is allowed for the125 // current route, if the current request can not be routed.126 // If this is the case, the request is answered with 'Method Not Allowed'127 // and HTTP status code 405.128 // If no other Method is allowed, the request is delegated to the NotFound129 // handler.130 HandleMethodNotAllowed bool131132 // ForwardedByClientIP if enabled, client IP will be parsed from the request's headers that133 // match those stored at `(*gin.Engine).RemoteIPHeaders`. If no IP was134 // fetched, it falls back to the IP obtained from135 // `(*gin.Context).Request.RemoteAddr`.136 ForwardedByClientIP bool137138 // AppEngine was deprecated.139 // Deprecated: USE `TrustedPlatform` WITH VALUE `gin.PlatformGoogleAppEngine` INSTEAD140 // #726 #755 If enabled, it will trust some headers starting with141 // 'X-AppEngine...' for better integration with that PaaS.142 AppEngine bool143144 // UseRawPath if enabled, the url.RawPath will be used to find parameters.145 // The RawPath is only a hint, EscapedPath() should be use instead. (https://pkg.go.dev/net/url@master#URL)146 // Only use RawPath if you know what you are doing.147 UseRawPath bool148149 // UseEscapedPath if enable, the url.EscapedPath() will be used to find parameters150 // It overrides UseRawPath151 UseEscapedPath bool152153 // UnescapePathValues if true, the path value will be unescaped.154 // If UseRawPath and UseEscapedPath are false (by default), the UnescapePathValues effectively is true,155 // as url.Path gonna be used, which is already unescaped.156 UnescapePathValues bool157158 // RemoveExtraSlash a parameter can be parsed from the URL even with extra slashes.159 // See the PR #1817 and issue #1644160 RemoveExtraSlash bool161162 // RemoteIPHeaders list of headers used to obtain the client IP when163 // `(*gin.Engine).ForwardedByClientIP` is `true` and164 // `(*gin.Context).Request.RemoteAddr` is matched by at least one of the165 // network origins of list defined by `(*gin.Engine).SetTrustedProxies()`.166 RemoteIPHeaders []string167168 // TrustedPlatform if set to a constant of value gin.Platform*, trusts the headers set by169 // that platform, for example to determine the client IP170 TrustedPlatform string171172 // MaxMultipartMemory value of 'maxMemory' param that is given to http.Request's ParseMultipartForm173 // method call.174 MaxMultipartMemory int64175176 // ReadHeaderTimeout is the maximum duration allowed for reading the request177 // headers by the http.Server created through Run, RunTLS and RunListener.178 // If zero or negative, a default of 10 seconds is used. Set to a positive179 // value to customize, or use a custom http.Server directly to disable it.180 ReadHeaderTimeout time.Duration181182 // UseH2C enable h2c support.183 UseH2C bool184185 // ContextWithFallback enable fallback Context.Deadline(), Context.Done(), Context.Err() and Context.Value() when Context.Request.Context() is not nil.186 ContextWithFallback bool187188 delims render.Delims189 secureJSONPrefix string190 HTMLRender render.HTMLRender191 FuncMap template.FuncMap192 allNoRoute HandlersChain193 allNoMethod HandlersChain194 noRoute HandlersChain195 noMethod HandlersChain196 pool sync.Pool197 trees methodTrees198 maxParams uint16199 maxSections uint16200 trustedProxies []string201 trustedCIDRs []*net.IPNet202}203204var _ IRouter = (*Engine)(nil)205206// New returns a new blank Engine instance without any middleware attached.207// By default, the configuration is:208// - RedirectTrailingSlash: true209// - RedirectFixedPath: false210// - HandleMethodNotAllowed: false211// - ForwardedByClientIP: true212// - UseRawPath: false213// - UseEscapedPath: false214// - UnescapePathValues: true215func New(opts ...OptionFunc) *Engine {216 debugPrintWARNINGNew()217 engine := &Engine{218 RouterGroup: RouterGroup{219 Handlers: nil,220 basePath: "/",221 root: true,222 },223 FuncMap: template.FuncMap{},224 RedirectTrailingSlash: true,225 RedirectFixedPath: false,226 HandleMethodNotAllowed: false,227 ForwardedByClientIP: true,228 RemoteIPHeaders: []string{"X-Forwarded-For", "X-Real-IP"},229 TrustedPlatform: defaultPlatform,230 UseRawPath: false,231 UseEscapedPath: false,232 RemoveExtraSlash: false,233 UnescapePathValues: true,234 MaxMultipartMemory: defaultMultipartMemory,235 ReadHeaderTimeout: defaultReadHeaderTimeout,236 trees: make(methodTrees, 0, 9),237 delims: render.Delims{Left: "{{", Right: "}}"},238 secureJSONPrefix: "while(1);",239 trustedProxies: []string{"0.0.0.0/0", "::/0"},240 trustedCIDRs: defaultTrustedCIDRs,241 }242 engine.engine = engine243 engine.pool.New = func() any {244 return engine.allocateContext(engine.maxParams)245 }246 return engine.With(opts...)247}248249// Default returns an Engine instance with the Logger and Recovery middleware already attached.250func Default(opts ...OptionFunc) *Engine {251 debugPrintWARNINGDefault()252 engine := New()253 engine.Use(Logger(), Recovery())254 return engine.With(opts...)255}256257func (engine *Engine) Handler() http.Handler {258 if !engine.UseH2C {259 return engine260 }261262 h2s := &http2.Server{}263 return h2c.NewHandler(engine, h2s)264}265266func (engine *Engine) allocateContext(maxParams uint16) *Context {267 v := make(Params, 0, maxParams)268 skippedNodes := make([]skippedNode, 0, engine.maxSections)269 return &Context{engine: engine, params: &v, skippedNodes: &skippedNodes}270}271272// getReadHeaderTimeout returns the configured ReadHeaderTimeout, or the273// default if it is zero or negative.274func (engine *Engine) getReadHeaderTimeout() time.Duration {275 if engine.ReadHeaderTimeout <= 0 {276 return defaultReadHeaderTimeout277 }278 return engine.ReadHeaderTimeout279}280281// Delims sets template left and right delims and returns an Engine instance.282func (engine *Engine) Delims(left, right string) *Engine {283 engine.delims = render.Delims{Left: left, Right: right}284 return engine285}286287// SecureJsonPrefix sets the secureJSONPrefix used in Context.SecureJSON.288func (engine *Engine) SecureJsonPrefix(prefix string) *Engine {289 engine.secureJSONPrefix = prefix290 return engine291}292293// LoadHTMLGlob loads HTML files identified by glob pattern294// and associates the result with HTML renderer.295func (engine *Engine) LoadHTMLGlob(pattern string) {296 left := engine.delims.Left297 right := engine.delims.Right298 templ := template.Must(template.New("").Delims(left, right).Funcs(engine.FuncMap).ParseGlob(pattern))299300 if IsDebugging() {301 debugPrintLoadTemplate(templ)302 engine.HTMLRender = render.HTMLDebug{Glob: pattern, FuncMap: engine.FuncMap, Delims: engine.delims}303 return304 }305306 engine.SetHTMLTemplate(templ)307}308309// LoadHTMLFiles loads a slice of HTML files310// and associates the result with HTML renderer.311func (engine *Engine) LoadHTMLFiles(files ...string) {312 if IsDebugging() {313 engine.HTMLRender = render.HTMLDebug{Files: files, FuncMap: engine.FuncMap, Delims: engine.delims}314 return315 }316317 templ := template.Must(template.New("").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap).ParseFiles(files...))318 engine.SetHTMLTemplate(templ)319}320321// LoadHTMLFS loads an http.FileSystem and a slice of patterns322// and associates the result with HTML renderer.323func (engine *Engine) LoadHTMLFS(fs http.FileSystem, patterns ...string) {324 if IsDebugging() {325 engine.HTMLRender = render.HTMLDebug{FileSystem: fs, Patterns: patterns, FuncMap: engine.FuncMap, Delims: engine.delims}326 return327 }328329 templ := template.Must(template.New("").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap).ParseFS(330 filesystem.FileSystem{FileSystem: fs}, patterns...))331 engine.SetHTMLTemplate(templ)332}333334// SetHTMLTemplate associate a template with HTML renderer.335func (engine *Engine) SetHTMLTemplate(templ *template.Template) {336 if len(engine.trees) > 0 {337 debugPrintWARNINGSetHTMLTemplate()338 }339340 engine.HTMLRender = render.HTMLProduction{Template: templ.Funcs(engine.FuncMap)}341}342343// SetFuncMap sets the FuncMap used for template.FuncMap.344func (engine *Engine) SetFuncMap(funcMap template.FuncMap) {345 engine.FuncMap = funcMap346}347348// NoRoute adds handlers for NoRoute. It returns a 404 code by default.349func (engine *Engine) NoRoute(handlers ...HandlerFunc) {350 engine.noRoute = handlers351 engine.rebuild404Handlers()352}353354// NoMethod sets the handlers called when Engine.HandleMethodNotAllowed = true.355func (engine *Engine) NoMethod(handlers ...HandlerFunc) {356 engine.noMethod = handlers357 engine.rebuild405Handlers()358}359360// Use attaches a global middleware to the router. i.e. the middleware attached through Use() will be361// included in the handlers chain for every single request. Even 404, 405, static files...362// For example, this is the right place for a logger or error management middleware.363func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes {364 engine.RouterGroup.Use(middleware...)365 engine.rebuild404Handlers()366 engine.rebuild405Handlers()367 return engine368}369370// With returns an Engine with the configuration set in the OptionFunc.371func (engine *Engine) With(opts ...OptionFunc) *Engine {372 for _, opt := range opts {373 opt(engine)374 }375376 return engine377}378379func (engine *Engine) rebuild404Handlers() {380 engine.allNoRoute = engine.combineHandlers(engine.noRoute)381}382383func (engine *Engine) rebuild405Handlers() {384 engine.allNoMethod = engine.combineHandlers(engine.noMethod)385}386387func (engine *Engine) addRoute(method, path string, handlers HandlersChain) {388 assert1(path[0] == '/', "path must begin with '/'")389 assert1(method != "", "HTTP method can not be empty")390 assert1(len(handlers) > 0, "there must be at least one handler")391392 debugPrintRoute(method, path, handlers)393394 root := engine.trees.get(method)395 if root == nil {396 root = new(node)397 root.fullPath = "/"398 engine.trees = append(engine.trees, methodTree{method: method, root: root})399 }400 root.addRoute(path, handlers)401402 if paramsCount := countParams(path); paramsCount > engine.maxParams {403 engine.maxParams = paramsCount404 }405406 if sectionsCount := countSections(path); sectionsCount > engine.maxSections {407 engine.maxSections = sectionsCount408 }409}410411// Routes returns a slice of registered routes, including some useful information, such as:412// the http method, path, and the handler name.413func (engine *Engine) Routes() (routes RoutesInfo) {414 for _, tree := range engine.trees {415 routes = iterate("", tree.method, routes, tree.root)416 }417 return routes418}419420func iterate(path, method string, routes RoutesInfo, root *node) RoutesInfo {421 path += root.path422 if len(root.handlers) > 0 {423 handlerFunc := root.handlers.Last()424 routes = append(routes, RouteInfo{425 Method: method,426 Path: path,427 Handler: nameOfFunction(handlerFunc),428 HandlerFunc: handlerFunc,429 })430 }431 for _, child := range root.children {432 routes = iterate(path, method, routes, child)433 }434 return routes435}436437func (engine *Engine) prepareTrustedCIDRs() ([]*net.IPNet, error) {438 if engine.trustedProxies == nil {439 return nil, nil440 }441442 cidr := make([]*net.IPNet, 0, len(engine.trustedProxies))443 for _, trustedProxy := range engine.trustedProxies {444 if !strings.Contains(trustedProxy, "/") {445 ip := parseIP(trustedProxy)446 if ip == nil {447 return cidr, &net.ParseError{Type: "IP address", Text: trustedProxy}448 }449450 switch len(ip) {451 case net.IPv4len:452 trustedProxy += "/32"453 case net.IPv6len:454 trustedProxy += "/128"455 }456 }457 _, cidrNet, err := net.ParseCIDR(trustedProxy)458 if err != nil {459 return cidr, err460 }461 cidr = append(cidr, cidrNet)462 }463 return cidr, nil464}465466// SetTrustedProxies set a list of network origins (IPv4 addresses,467// IPv4 CIDRs, IPv6 addresses or IPv6 CIDRs) from which to trust468// request's headers that contain alternative client IP when469// `(*gin.Engine).ForwardedByClientIP` is `true`. `TrustedProxies`470// feature is enabled by default, and it also trusts all proxies471// by default. If you want to disable this feature, use472// Engine.SetTrustedProxies(nil), then Context.ClientIP() will473// return the remote address directly.474func (engine *Engine) SetTrustedProxies(trustedProxies []string) error {475 engine.trustedProxies = trustedProxies476 return engine.parseTrustedProxies()477}478479// isUnsafeTrustedProxies checks if Engine.trustedCIDRs contains all IPs, it's not safe if it has (returns true)480func (engine *Engine) isUnsafeTrustedProxies() bool {481 return engine.isTrustedProxy(net.ParseIP("0.0.0.0")) || engine.isTrustedProxy(net.ParseIP("::"))482}483484// parseTrustedProxies parse Engine.trustedProxies to Engine.trustedCIDRs485func (engine *Engine) parseTrustedProxies() error {486 trustedCIDRs, err := engine.prepareTrustedCIDRs()487 engine.trustedCIDRs = trustedCIDRs488 return err489}490491// isTrustedProxy will check whether the IP address is included in the trusted list according to Engine.trustedCIDRs492func (engine *Engine) isTrustedProxy(ip net.IP) bool {493 if engine.trustedCIDRs == nil {494 return false495 }496 for _, cidr := range engine.trustedCIDRs {497 if cidr.Contains(ip) {498 return true499 }500 }501 return false502}503504// validateHeader will parse X-Forwarded-For header and return the trusted client IP address505func (engine *Engine) validateHeader(header string) (clientIP string, valid bool) {506 if header == "" {507 return "", false508 }509 items := strings.Split(header, ",")510 for i := len(items) - 1; i >= 0; i-- {511 ipStr := strings.TrimSpace(items[i])512 ip := net.ParseIP(ipStr)513 if ip == nil {514 break515 }516517 // X-Forwarded-For is appended by proxy518 // Check IPs in reverse order and stop when find untrusted proxy519 if (i == 0) || (!engine.isTrustedProxy(ip)) {520 return ipStr, true521 }522 }523 return "", false524}525526// updateRouteTree do update to the route tree recursively527func updateRouteTree(n *node) {528 n.path = strings.ReplaceAll(n.path, escapedColon, colon)529 n.fullPath = strings.ReplaceAll(n.fullPath, escapedColon, colon)530 n.indices = strings.ReplaceAll(n.indices, backslash, colon)531 if n.children == nil {532 return533 }534 for _, child := range n.children {535 updateRouteTree(child)536 }537}538539// updateRouteTrees do update to the route trees540func (engine *Engine) updateRouteTrees() {541 for _, tree := range engine.trees {542 updateRouteTree(tree.root)543 }544}545546// parseIP parse a string representation of an IP and returns a net.IP with the547// minimum byte representation or nil if input is invalid.548func parseIP(ip string) net.IP {549 parsedIP := net.ParseIP(ip)550551 if ipv4 := parsedIP.To4(); ipv4 != nil {552 // return ip in a 4-byte representation553 return ipv4554 }555556 // return ip in a 16-byte representation or nil557 return parsedIP558}559560// Run attaches the router to a http.Server and starts listening and serving HTTP requests.561// It is a shortcut for http.ListenAndServe(addr, router)562// Note: this method will block the calling goroutine indefinitely unless an error happens.563// The created http.Server is configured with a default ReadHeaderTimeout of 10 seconds564// (configurable via Engine.ReadHeaderTimeout) to mitigate slowloris attacks.565// For full control over timeouts, create a custom http.Server and use ServeHTTP.566func (engine *Engine) Run(addr ...string) (err error) {567 defer func() { debugPrintError(err) }()568569 if engine.isUnsafeTrustedProxies() {570 debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" +571 "Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.")572 }573 engine.updateRouteTrees()574 address := resolveAddress(addr)575 debugPrint("Listening and serving HTTP on %s\n", address)576 server := &http.Server{ // #nosec G112577 Addr: address,578 Handler: engine.Handler(),579 ReadHeaderTimeout: engine.getReadHeaderTimeout(),580 }581 err = server.ListenAndServe()582 return583}584585// RunTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests.586// It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router)587// Note: this method will block the calling goroutine indefinitely unless an error happens.588func (engine *Engine) RunTLS(addr, certFile, keyFile string) (err error) {589 debugPrint("Listening and serving HTTPS on %s\n", addr)590 defer func() { debugPrintError(err) }()591592 if engine.isUnsafeTrustedProxies() {593 debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" +594 "Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.")595 }596597 server := &http.Server{ // #nosec G112598 Addr: addr,599 Handler: engine.Handler(),600 ReadHeaderTimeout: engine.getReadHeaderTimeout(),601 }602 err = server.ListenAndServeTLS(certFile, keyFile)603 return604}605606// RunUnix attaches the router to a http.Server and starts listening and serving HTTP requests607// through the specified unix socket (i.e. a file).608// Note: this method will block the calling goroutine indefinitely unless an error happens.609func (engine *Engine) RunUnix(file string) (err error) {610 debugPrint("Listening and serving HTTP on unix:/%s", file)611 defer func() { debugPrintError(err) }()612613 if engine.isUnsafeTrustedProxies() {614 debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" +615 "Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.")616 }617618 listener, err := net.Listen("unix", file)619 if err != nil {620 return621 }622 defer listener.Close()623 defer os.Remove(file)624625 server := &http.Server{ // #nosec G112626 Handler: engine.Handler(),627 }628 err = server.Serve(listener)629 return630}631632// RunFd attaches the router to a http.Server and starts listening and serving HTTP requests633// through the specified file descriptor.634// Note: this method will block the calling goroutine indefinitely unless an error happens.635func (engine *Engine) RunFd(fd int) (err error) {636 debugPrint("Listening and serving HTTP on fd@%d", fd)637 defer func() { debugPrintError(err) }()638639 if engine.isUnsafeTrustedProxies() {640 debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" +641 "Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.")642 }643644 f := os.NewFile(uintptr(fd), fmt.Sprintf("fd@%d", fd))645 defer f.Close()646 listener, err := net.FileListener(f)647 if err != nil {648 return649 }650 defer listener.Close()651 err = engine.RunListener(listener)652 return653}654655// RunQUIC attaches the router to a http.Server and starts listening and serving QUIC requests.656// It is a shortcut for http3.ListenAndServeQUIC(addr, certFile, keyFile, router)657// Note: this method will block the calling goroutine indefinitely unless an error happens.658func (engine *Engine) RunQUIC(addr, certFile, keyFile string) (err error) {659 debugPrint("Listening and serving QUIC on %s\n", addr)660 defer func() { debugPrintError(err) }()661662 if engine.isUnsafeTrustedProxies() {663 debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" +664 "Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.")665 }666667 err = http3.ListenAndServeQUIC(addr, certFile, keyFile, engine.Handler())668 return669}670671// RunListener attaches the router to a http.Server and starts listening and serving HTTP requests672// through the specified net.Listener673func (engine *Engine) RunListener(listener net.Listener) (err error) {674 debugPrint("Listening and serving HTTP on listener what's bind with address@%s", listener.Addr())675 defer func() { debugPrintError(err) }()676677 if engine.isUnsafeTrustedProxies() {678 debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n" +679 "Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.")680 }681682 server := &http.Server{ // #nosec G112683 Handler: engine.Handler(),684 ReadHeaderTimeout: engine.getReadHeaderTimeout(),685 }686 err = server.Serve(listener)687 return688}689690// ServeHTTP conforms to the http.Handler interface.691func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {692 engine.routeTreesUpdated.Do(func() {693 engine.updateRouteTrees()694 })695696 c := engine.pool.Get().(*Context)697 c.writermem.reset(w)698 c.Request = req699 c.reset()700701 engine.handleHTTPRequest(c)702703 engine.pool.Put(c)704}705706// HandleContext re-enters a context that has been rewritten.707// This can be done by setting c.Request.URL.Path to your new target.708// Disclaimer: You can loop yourself to deal with this, use wisely.709func (engine *Engine) HandleContext(c *Context) {710 oldIndexValue := c.index711 oldHandlers := c.handlers712 c.reset()713 engine.handleHTTPRequest(c)714715 c.index = oldIndexValue716 c.handlers = oldHandlers717}718719func (engine *Engine) handleHTTPRequest(c *Context) {720 httpMethod := c.Request.Method721 rPath := c.Request.URL.Path722 unescape := false723724 if engine.UseEscapedPath {725 rPath = c.Request.URL.EscapedPath()726 unescape = engine.UnescapePathValues727 } else if engine.UseRawPath && len(c.Request.URL.RawPath) > 0 {728 rPath = c.Request.URL.RawPath729 unescape = engine.UnescapePathValues730 }731732 if engine.RemoveExtraSlash {733 rPath = cleanPath(rPath)734 }735736 // Find root of the tree for the given HTTP method737 t := engine.trees738 for i, tl := 0, len(t); i < tl; i++ {739 if t[i].method != httpMethod {740 continue741 }742 root := t[i].root743 // Find route in tree744 value := root.getValue(rPath, c.params, c.skippedNodes, unescape)745 if value.params != nil {746 c.Params = *value.params747 }748 if value.handlers != nil {749 c.handlers = value.handlers750 c.fullPath = value.fullPath751 c.Next()752 c.writermem.WriteHeaderNow()753 return754 }755 if httpMethod != http.MethodConnect && rPath != "/" {756 if value.tsr && engine.RedirectTrailingSlash {757 redirectTrailingSlash(c)758 return759 }760 if engine.RedirectFixedPath && redirectFixedPath(c, root, engine.RedirectFixedPath) {761 return762 }763 }764 break765 }766767 if engine.HandleMethodNotAllowed && len(t) > 0 {768 // According to RFC 7231 section 6.5.5, MUST generate an Allow header field in response769 // containing a list of the target resource's currently supported methods.770 allowed := make([]string, 0, len(t)-1)771 for _, tree := range engine.trees {772 if tree.method == httpMethod {773 continue774 }775 if value := tree.root.getValue(rPath, nil, c.skippedNodes, unescape); value.handlers != nil {776 allowed = append(allowed, tree.method)777 }778 }779 if len(allowed) > 0 {780 c.handlers = engine.allNoMethod781 c.writermem.Header().Set("Allow", strings.Join(allowed, ", "))782 serveError(c, http.StatusMethodNotAllowed, default405Body)783 return784 }785 }786787 c.handlers = engine.allNoRoute788 serveError(c, http.StatusNotFound, default404Body)789}790791var mimePlain = []string{MIMEPlain}792793func serveError(c *Context, code int, defaultMessage []byte) {794 c.writermem.status = code795 c.Next()796 if c.writermem.Written() {797 return798 }799 if c.writermem.Status() == code {800 c.writermem.Header()["Content-Type"] = mimePlain801 _, err := c.Writer.Write(defaultMessage)802 if err != nil {803 debugPrint("cannot write message to writer during serve error: %v", err)804 }805 return806 }807 c.writermem.WriteHeaderNow()808}809810func redirectTrailingSlash(c *Context) {811 req := c.Request812 p := req.URL.Path813 if prefix := path.Clean(c.Request.Header.Get("X-Forwarded-Prefix")); prefix != "." {814 prefix = sanitizePathChars(prefix)815 prefix = removeRepeatedChar(prefix, '/')816817 p = prefix + "/" + req.URL.Path818 }819 req.URL.Path = p + "/"820 if length := len(p); length > 1 && p[length-1] == '/' {821 req.URL.Path = p[:length-1]822 }823 redirectRequest(c)824}825826// sanitizePathChars removes unsafe characters from path strings,827// keeping only ASCII letters, ASCII numbers, forward slashes, and hyphens.828func sanitizePathChars(s string) string {829 return strings.Map(func(r rune) rune {830 if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '/' || r == '-' {831 return r832 }833 return -1834 }, s)835}836837func redirectFixedPath(c *Context, root *node, trailingSlash bool) bool {838 req := c.Request839 rPath := req.URL.Path840841 if fixedPath, ok := root.findCaseInsensitivePath(cleanPath(rPath), trailingSlash); ok {842 req.URL.Path = bytesconv.BytesToString(fixedPath)843 redirectRequest(c)844 return true845 }846 return false847}848849func redirectRequest(c *Context) {850 req := c.Request851 rPath := req.URL.Path852 rURL := req.URL.String()853854 code := http.StatusMovedPermanently // Permanent redirect, request with GET method855 if req.Method != http.MethodGet {856 code = http.StatusTemporaryRedirect857 }858 debugPrint("redirecting request %d: %s --> %s", code, rPath, rURL)859 http.Redirect(c.Writer, req, rURL, code)860 c.writermem.WriteHeaderNow()861}