context.go
This file
Path
context.go
1,543 lines · 47.2 KiB · Go
Last changed by
docs: fix SecureJSON default prefix and default-binding example output (#4861)Zain Qureshibefore adoption43fe48e
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 "errors"9 "fmt"10 "io"11 "io/fs"12 "log"13 "maps"14 "math"15 "mime/multipart"16 "net"17 "net/http"18 "net/url"19 "os"20 "path/filepath"21 "strings"22 "sync"23 "time"2425 "github.com/gin-contrib/sse"26 "github.com/gin-gonic/gin/binding"27 "github.com/gin-gonic/gin/render"28)2930// Content-Type MIME of the most common data formats.31const (32 MIMEJSON = binding.MIMEJSON33 MIMEHTML = binding.MIMEHTML34 MIMEXML = binding.MIMEXML35 MIMEXML2 = binding.MIMEXML236 MIMEPlain = binding.MIMEPlain37 MIMEPOSTForm = binding.MIMEPOSTForm38 MIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm39 MIMEYAML = binding.MIMEYAML40 MIMEYAML2 = binding.MIMEYAML241 MIMETOML = binding.MIMETOML42 MIMEPROTOBUF = binding.MIMEPROTOBUF43 MIMEBSON = binding.MIMEBSON44)4546// BodyBytesKey indicates a default body bytes key.47const BodyBytesKey = "_gin-gonic/gin/bodybyteskey"4849// ContextKey is the key that a Context returns itself for.50const ContextKey = "_gin-gonic/gin/contextkey"5152type ContextKeyType int5354const ContextRequestKey ContextKeyType = 05556// abortIndex represents a typical value used in abort functions.57const abortIndex int8 = math.MaxInt8 >> 15859// Context is the most important part of gin. It allows us to pass variables between middleware,60// manage the flow, validate the JSON of a request and render a JSON response for example.61type Context struct {62 writermem responseWriter63 Request *http.Request64 Writer ResponseWriter6566 Params Params67 handlers HandlersChain68 index int869 fullPath string7071 engine *Engine72 params *Params73 skippedNodes *[]skippedNode7475 // This mutex protects Keys map.76 mu sync.RWMutex7778 // Keys is a key/value pair exclusively for the context of each request.79 Keys map[any]any8081 // Errors is a list of errors attached to all the handlers/middlewares who used this context.82 Errors errorMsgs8384 // Accepted defines a list of manually accepted formats for content negotiation.85 Accepted []string8687 // queryCache caches the query result from c.Request.URL.Query().88 queryCache url.Values8990 // formCache caches c.Request.PostForm, which contains the parsed form data from POST, PATCH,91 // or PUT body parameters.92 formCache url.Values9394 // SameSite allows a server to define a cookie attribute making it impossible for95 // the browser to send this cookie along with cross-site requests.96 sameSite http.SameSite97}9899/************************************/100/********** CONTEXT CREATION ********/101/************************************/102103func (c *Context) reset() {104 c.Writer = &c.writermem105 c.Params = c.Params[:0]106 c.handlers = nil107 c.index = -1108109 c.fullPath = ""110 c.Keys = nil111 c.Errors = c.Errors[:0]112 c.Accepted = nil113 c.queryCache = nil114 c.formCache = nil115 c.sameSite = 0116 *c.params = (*c.params)[:0]117 *c.skippedNodes = (*c.skippedNodes)[:0]118}119120// Copy returns a copy of the current context that can be safely used outside the request's scope.121// This has to be used when the context has to be passed to a goroutine.122func (c *Context) Copy() *Context {123 cp := Context{124 writermem: c.writermem,125 Request: c.Request,126 engine: c.engine,127 }128129 cp.writermem.ResponseWriter = nil130 cp.Writer = &cp.writermem131 cp.index = abortIndex132 cp.handlers = nil133 cp.fullPath = c.fullPath134135 c.mu.RLock()136 cp.Keys = maps.Clone(c.Keys)137 c.mu.RUnlock()138139 cParams := c.Params140 cp.Params = make([]Param, len(cParams))141 copy(cp.Params, cParams)142143 if c.Errors != nil {144 cp.Errors = make(errorMsgs, len(c.Errors))145 copy(cp.Errors, c.Errors)146 }147148 if c.Accepted != nil {149 cp.Accepted = make([]string, len(c.Accepted))150 copy(cp.Accepted, c.Accepted)151 }152153 return &cp154}155156// HandlerName returns the main handler's name. For example if the handler is "handleGetUsers()",157// this function will return "main.handleGetUsers".158func (c *Context) HandlerName() string {159 return nameOfFunction(c.handlers.Last())160}161162// HandlerNames returns a list of all registered handlers for this context in descending order,163// following the semantics of HandlerName()164func (c *Context) HandlerNames() []string {165 hn := make([]string, 0, len(c.handlers))166 for _, val := range c.handlers {167 if val == nil {168 continue169 }170 hn = append(hn, nameOfFunction(val))171 }172 return hn173}174175// Handler returns the main handler.176func (c *Context) Handler() HandlerFunc {177 return c.handlers.Last()178}179180// FullPath returns a matched route full path. For not found routes181// returns an empty string.182//183// router.GET("/user/:id", func(c *gin.Context) {184// c.FullPath() == "/user/:id" // true185// })186func (c *Context) FullPath() string {187 return c.fullPath188}189190/************************************/191/*********** FLOW CONTROL ***********/192/************************************/193194// Next should be used only inside middleware.195// It executes the pending handlers in the chain inside the calling handler.196// See example in GitHub.197func (c *Context) Next() {198 c.index++199 for c.index < safeInt8(len(c.handlers)) {200 if c.handlers[c.index] != nil {201 c.handlers[c.index](c)202 }203 c.index++204 }205}206207// IsAborted returns true if the current context was aborted.208func (c *Context) IsAborted() bool {209 return c.index >= abortIndex210}211212// Abort prevents pending handlers from being called. Note that this will not stop the current handler.213// Let's say you have an authorization middleware that validates that the current request is authorized.214// If the authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers215// for this request are not called.216func (c *Context) Abort() {217 c.index = abortIndex218}219220// AbortWithStatus calls `Abort()` and writes the headers with the specified status code.221// For example, a failed attempt to authenticate a request could use: context.AbortWithStatus(401).222func (c *Context) AbortWithStatus(code int) {223 c.Status(code)224 c.Writer.WriteHeaderNow()225 c.Abort()226}227228// AbortWithStatusPureJSON calls `Abort()` and then `PureJSON` internally.229// This method stops the chain, writes the status code and return a JSON body without escaping.230// It also sets the Content-Type as "application/json".231func (c *Context) AbortWithStatusPureJSON(code int, jsonObj any) {232 c.Abort()233 c.PureJSON(code, jsonObj)234}235236// AbortWithStatusJSON calls `Abort()` and then `JSON` internally.237// This method stops the chain, writes the status code and return a JSON body.238// It also sets the Content-Type as "application/json".239func (c *Context) AbortWithStatusJSON(code int, jsonObj any) {240 c.Abort()241 c.JSON(code, jsonObj)242}243244// AbortWithError calls `AbortWithStatus()` and `Error()` internally.245// This method stops the chain, writes the status code and pushes the specified error to `c.Errors`.246// See Context.Error() for more details.247func (c *Context) AbortWithError(code int, err error) *Error {248 c.AbortWithStatus(code)249 return c.Error(err)250}251252/************************************/253/********* ERROR MANAGEMENT *********/254/************************************/255256// Error attaches an error to the current context. The error is pushed to a list of errors.257// It's a good idea to call Error for each error that occurred during the resolution of a request.258// A middleware can be used to collect all the errors and push them to a database together,259// print a log, or append it in the HTTP response.260// Error will panic if err is nil.261func (c *Context) Error(err error) *Error {262 if err == nil {263 panic("err is nil")264 }265266 var parsedError *Error267 ok := errors.As(err, &parsedError)268 if !ok {269 parsedError = &Error{270 Err: err,271 Type: ErrorTypePrivate,272 }273 }274275 c.Errors = append(c.Errors, parsedError)276 return parsedError277}278279/************************************/280/******** METADATA MANAGEMENT********/281/************************************/282283// Set is used to store a new key/value pair exclusively for this context.284// It also lazy initializes c.Keys if it was not used previously.285func (c *Context) Set(key any, value any) {286 c.mu.Lock()287 defer c.mu.Unlock()288 if c.Keys == nil {289 c.Keys = make(map[any]any)290 }291292 c.Keys[key] = value293}294295// Get returns the value for the given key, ie: (value, true).296// If the value does not exist it returns (nil, false)297func (c *Context) Get(key any) (value any, exists bool) {298 c.mu.RLock()299 defer c.mu.RUnlock()300 value, exists = c.Keys[key]301 return302}303304// MustGet returns the value for the given key if it exists, otherwise it panics.305func (c *Context) MustGet(key any) any {306 if value, exists := c.Get(key); exists {307 return value308 }309 panic(fmt.Sprintf("key %v does not exist", key))310}311312func getTyped[T any](c *Context, key any) (res T) {313 if val, ok := c.Get(key); ok && val != nil {314 res, _ = val.(T)315 }316 return317}318319// GetString returns the value associated with the key as a string.320func (c *Context) GetString(key any) string {321 return getTyped[string](c, key)322}323324// GetBool returns the value associated with the key as a boolean.325func (c *Context) GetBool(key any) bool {326 return getTyped[bool](c, key)327}328329// GetInt returns the value associated with the key as an integer.330func (c *Context) GetInt(key any) int {331 return getTyped[int](c, key)332}333334// GetInt8 returns the value associated with the key as an integer 8.335func (c *Context) GetInt8(key any) int8 {336 return getTyped[int8](c, key)337}338339// GetInt16 returns the value associated with the key as an integer 16.340func (c *Context) GetInt16(key any) int16 {341 return getTyped[int16](c, key)342}343344// GetInt32 returns the value associated with the key as an integer 32.345func (c *Context) GetInt32(key any) int32 {346 return getTyped[int32](c, key)347}348349// GetInt64 returns the value associated with the key as an integer 64.350func (c *Context) GetInt64(key any) int64 {351 return getTyped[int64](c, key)352}353354// GetUint returns the value associated with the key as an unsigned integer.355func (c *Context) GetUint(key any) uint {356 return getTyped[uint](c, key)357}358359// GetUint8 returns the value associated with the key as an unsigned integer 8.360func (c *Context) GetUint8(key any) uint8 {361 return getTyped[uint8](c, key)362}363364// GetUint16 returns the value associated with the key as an unsigned integer 16.365func (c *Context) GetUint16(key any) uint16 {366 return getTyped[uint16](c, key)367}368369// GetUint32 returns the value associated with the key as an unsigned integer 32.370func (c *Context) GetUint32(key any) uint32 {371 return getTyped[uint32](c, key)372}373374// GetUint64 returns the value associated with the key as an unsigned integer 64.375func (c *Context) GetUint64(key any) uint64 {376 return getTyped[uint64](c, key)377}378379// GetFloat32 returns the value associated with the key as a float32.380func (c *Context) GetFloat32(key any) float32 {381 return getTyped[float32](c, key)382}383384// GetFloat64 returns the value associated with the key as a float64.385func (c *Context) GetFloat64(key any) float64 {386 return getTyped[float64](c, key)387}388389// GetTime returns the value associated with the key as time.390func (c *Context) GetTime(key any) time.Time {391 return getTyped[time.Time](c, key)392}393394// GetDuration returns the value associated with the key as a duration.395func (c *Context) GetDuration(key any) time.Duration {396 return getTyped[time.Duration](c, key)397}398399// GetError returns the value associated with the key as an error.400func (c *Context) GetError(key any) error {401 return getTyped[error](c, key)402}403404// GetIntSlice returns the value associated with the key as a slice of integers.405func (c *Context) GetIntSlice(key any) []int {406 return getTyped[[]int](c, key)407}408409// GetInt8Slice returns the value associated with the key as a slice of int8 integers.410func (c *Context) GetInt8Slice(key any) []int8 {411 return getTyped[[]int8](c, key)412}413414// GetInt16Slice returns the value associated with the key as a slice of int16 integers.415func (c *Context) GetInt16Slice(key any) []int16 {416 return getTyped[[]int16](c, key)417}418419// GetInt32Slice returns the value associated with the key as a slice of int32 integers.420func (c *Context) GetInt32Slice(key any) []int32 {421 return getTyped[[]int32](c, key)422}423424// GetInt64Slice returns the value associated with the key as a slice of int64 integers.425func (c *Context) GetInt64Slice(key any) []int64 {426 return getTyped[[]int64](c, key)427}428429// GetUintSlice returns the value associated with the key as a slice of unsigned integers.430func (c *Context) GetUintSlice(key any) []uint {431 return getTyped[[]uint](c, key)432}433434// GetUint8Slice returns the value associated with the key as a slice of uint8 integers.435func (c *Context) GetUint8Slice(key any) []uint8 {436 return getTyped[[]uint8](c, key)437}438439// GetUint16Slice returns the value associated with the key as a slice of uint16 integers.440func (c *Context) GetUint16Slice(key any) []uint16 {441 return getTyped[[]uint16](c, key)442}443444// GetUint32Slice returns the value associated with the key as a slice of uint32 integers.445func (c *Context) GetUint32Slice(key any) []uint32 {446 return getTyped[[]uint32](c, key)447}448449// GetUint64Slice returns the value associated with the key as a slice of uint64 integers.450func (c *Context) GetUint64Slice(key any) []uint64 {451 return getTyped[[]uint64](c, key)452}453454// GetFloat32Slice returns the value associated with the key as a slice of float32 numbers.455func (c *Context) GetFloat32Slice(key any) []float32 {456 return getTyped[[]float32](c, key)457}458459// GetFloat64Slice returns the value associated with the key as a slice of float64 numbers.460func (c *Context) GetFloat64Slice(key any) []float64 {461 return getTyped[[]float64](c, key)462}463464// GetStringSlice returns the value associated with the key as a slice of strings.465func (c *Context) GetStringSlice(key any) []string {466 return getTyped[[]string](c, key)467}468469// GetErrorSlice returns the value associated with the key as a slice of errors.470func (c *Context) GetErrorSlice(key any) []error {471 return getTyped[[]error](c, key)472}473474// GetStringMap returns the value associated with the key as a map of interfaces.475func (c *Context) GetStringMap(key any) map[string]any {476 return getTyped[map[string]any](c, key)477}478479// GetStringMapString returns the value associated with the key as a map of strings.480func (c *Context) GetStringMapString(key any) map[string]string {481 return getTyped[map[string]string](c, key)482}483484// GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.485func (c *Context) GetStringMapStringSlice(key any) map[string][]string {486 return getTyped[map[string][]string](c, key)487}488489// Delete deletes the key from the Context's Key map, if it exists.490// This operation is safe to be used by concurrent go-routines491func (c *Context) Delete(key any) {492 c.mu.Lock()493 defer c.mu.Unlock()494 if c.Keys != nil {495 delete(c.Keys, key)496 }497}498499/************************************/500/************ INPUT DATA ************/501/************************************/502503// Param returns the value of the URL param.504// It is a shortcut for c.Params.ByName(key)505//506// router.GET("/user/:id", func(c *gin.Context) {507// // a GET request to /user/john508// id := c.Param("id") // id == "john"509// // a GET request to /user/john/510// id := c.Param("id") // id == "/john/"511// })512func (c *Context) Param(key string) string {513 return c.Params.ByName(key)514}515516// AddParam adds param to context and517// replaces path param key with given value for e2e testing purposes518// Example Route: "/user/:id"519// AddParam("id", 1)520// Result: "/user/1"521func (c *Context) AddParam(key, value string) {522 c.Params = append(c.Params, Param{Key: key, Value: value})523}524525// Query returns the keyed url query value if it exists,526// otherwise it returns an empty string `("")`.527// It is shortcut for `c.Request.URL.Query().Get(key)`528//529// GET /path?id=1234&name=Manu&value=530// c.Query("id") == "1234"531// c.Query("name") == "Manu"532// c.Query("value") == ""533// c.Query("wtf") == ""534func (c *Context) Query(key string) (value string) {535 value, _ = c.GetQuery(key)536 return537}538539// DefaultQuery returns the keyed url query value if it exists,540// otherwise it returns the specified defaultValue string.541// See: Query() and GetQuery() for further information.542//543// GET /?name=Manu&lastname=544// c.DefaultQuery("name", "unknown") == "Manu"545// c.DefaultQuery("id", "none") == "none"546// c.DefaultQuery("lastname", "none") == ""547func (c *Context) DefaultQuery(key, defaultValue string) string {548 if value, ok := c.GetQuery(key); ok {549 return value550 }551 return defaultValue552}553554// GetQuery is like Query(), it returns the keyed url query value555// if it exists `(value, true)` (even when the value is an empty string),556// otherwise it returns `("", false)`.557// It is shortcut for `c.Request.URL.Query().Get(key)`558//559// GET /?name=Manu&lastname=560// ("Manu", true) == c.GetQuery("name")561// ("", false) == c.GetQuery("id")562// ("", true) == c.GetQuery("lastname")563func (c *Context) GetQuery(key string) (string, bool) {564 if values, ok := c.GetQueryArray(key); ok {565 return values[0], ok566 }567 return "", false568}569570// QueryArray returns a slice of strings for a given query key.571// The length of the slice depends on the number of params with the given key.572func (c *Context) QueryArray(key string) (values []string) {573 values, _ = c.GetQueryArray(key)574 return575}576577func (c *Context) initQueryCache() {578 if c.queryCache == nil {579 if c.Request != nil && c.Request.URL != nil {580 c.queryCache = c.Request.URL.Query()581 } else {582 c.queryCache = url.Values{}583 }584 }585}586587// GetQueryArray returns a slice of strings for a given query key, plus588// a boolean value whether at least one value exists for the given key.589func (c *Context) GetQueryArray(key string) (values []string, ok bool) {590 c.initQueryCache()591 values, ok = c.queryCache[key]592 return593}594595// QueryMap returns a map for a given query key.596func (c *Context) QueryMap(key string) (dicts map[string]string) {597 dicts, _ = c.GetQueryMap(key)598 return599}600601// GetQueryMap returns a map for a given query key, plus a boolean value602// whether at least one value exists for the given key.603func (c *Context) GetQueryMap(key string) (map[string]string, bool) {604 c.initQueryCache()605 return getMapFromFormData(c.queryCache, key)606}607608// PostForm returns the specified key from a POST urlencoded form or multipart form609// when it exists, otherwise it returns an empty string `("")`.610func (c *Context) PostForm(key string) (value string) {611 value, _ = c.GetPostForm(key)612 return613}614615// DefaultPostForm returns the specified key from a POST urlencoded form or multipart form616// when it exists, otherwise it returns the specified defaultValue string.617// See: PostForm() and GetPostForm() for further information.618func (c *Context) DefaultPostForm(key, defaultValue string) string {619 if value, ok := c.GetPostForm(key); ok {620 return value621 }622 return defaultValue623}624625// GetPostForm is like PostForm(key). It returns the specified key from a POST urlencoded626// form or multipart form when it exists `(value, true)` (even when the value is an empty string),627// otherwise it returns ("", false).628// For example, during a PATCH request to update the user's email:629//630// email=mail@example.com --> ("mail@example.com", true) := GetPostForm("email") // set email to "mail@example.com"631// email= --> ("", true) := GetPostForm("email") // set email to ""632// --> ("", false) := GetPostForm("email") // do nothing with email633func (c *Context) GetPostForm(key string) (string, bool) {634 if values, ok := c.GetPostFormArray(key); ok {635 return values[0], ok636 }637 return "", false638}639640// PostFormArray returns a slice of strings for a given form key.641// The length of the slice depends on the number of params with the given key.642func (c *Context) PostFormArray(key string) (values []string) {643 values, _ = c.GetPostFormArray(key)644 return645}646647func (c *Context) initFormCache() {648 if c.formCache == nil {649 c.formCache = make(url.Values)650 req := c.Request651 if err := req.ParseMultipartForm(c.engine.MaxMultipartMemory); err != nil {652 if !errors.Is(err, http.ErrNotMultipart) {653 debugPrint("error on parse multipart form array: %v", err)654 }655 }656 c.formCache = req.PostForm657 }658}659660// GetPostFormArray returns a slice of strings for a given form key, plus661// a boolean value whether at least one value exists for the given key.662func (c *Context) GetPostFormArray(key string) (values []string, ok bool) {663 c.initFormCache()664 values, ok = c.formCache[key]665 return666}667668// PostFormMap returns a map for a given form key.669func (c *Context) PostFormMap(key string) (dicts map[string]string) {670 dicts, _ = c.GetPostFormMap(key)671 return672}673674// GetPostFormMap returns a map for a given form key, plus a boolean value675// whether at least one value exists for the given key.676func (c *Context) GetPostFormMap(key string) (map[string]string, bool) {677 c.initFormCache()678 return getMapFromFormData(c.formCache, key)679}680681// getMapFromFormData return a map which satisfies conditions.682// It parses from data with bracket notation like "key[subkey]=value" into a map.683func getMapFromFormData(m map[string][]string, key string) (map[string]string, bool) {684 d := make(map[string]string)685 found := false686 keyLen := len(key)687688 for k, v := range m {689 if len(k) < keyLen+3 { // key + "[" + at least one char + "]"690 continue691 }692693 if k[:keyLen] != key || k[keyLen] != '[' {694 continue695 }696697 if j := strings.IndexByte(k[keyLen+1:], ']'); j > 0 {698 found = true699 d[k[keyLen+1:keyLen+1+j]] = v[0]700 }701 }702703 return d, found704}705706// FormFile returns the first file for the provided form key.707func (c *Context) FormFile(name string) (*multipart.FileHeader, error) {708 if c.Request.MultipartForm == nil {709 if err := c.Request.ParseMultipartForm(c.engine.MaxMultipartMemory); err != nil {710 return nil, err711 }712 }713 f, fh, err := c.Request.FormFile(name)714 if err != nil {715 return nil, err716 }717 f.Close()718 return fh, err719}720721// MultipartForm is the parsed multipart form, including file uploads.722func (c *Context) MultipartForm() (*multipart.Form, error) {723 err := c.Request.ParseMultipartForm(c.engine.MaxMultipartMemory)724 return c.Request.MultipartForm, err725}726727// SaveUploadedFile uploads the form file to specific dst.728// An optional perm argument specifies the permission bits used when creating729// the destination directory. If not provided, the default is 0750. The exact730// permission is enforced only on the destination directory and only when it is731// newly created by this call; pre-existing directories (e.g. /tmp) are not732// modified.733func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string, perm ...fs.FileMode) error {734 src, err := file.Open()735 if err != nil {736 return err737 }738 defer src.Close()739740 var mode os.FileMode = 0o750741 if len(perm) > 0 {742 mode = perm[0]743 }744 dir := filepath.Dir(dst)745 // Record whether the destination directory exists before MkdirAll, so we746 // only chmod a directory we just created. Chmod'ing a pre-existing directory747 // the process does not own (e.g. /tmp) fails with "operation not permitted"748 // (#4622). A non-ErrNotExist stat error also skips chmod and lets MkdirAll749 // surface the underlying failure.750 _, statErr := os.Stat(dir)751 if err = os.MkdirAll(dir, mode); err != nil {752 return err753 }754 if errors.Is(statErr, os.ErrNotExist) {755 if err = os.Chmod(dir, mode); err != nil {756 return err757 }758 }759760 out, err := os.Create(dst)761 if err != nil {762 return err763 }764 defer out.Close()765766 _, err = io.Copy(out, src)767 return err768}769770// Bind checks the Method and Content-Type to select a binding engine automatically,771// Depending on the "Content-Type" header different bindings are used, for example:772//773// "application/json" --> JSON binding774// "application/xml" --> XML binding775//776// It parses the request's body based on the Content-Type (e.g., JSON or XML).777// It decodes the payload into the struct specified as a pointer.778// It writes a 400 error and sets Content-Type header "text/plain" in the response if input is not valid.779func (c *Context) Bind(obj any) error {780 b := binding.Default(c.Request.Method, c.ContentType())781 return c.MustBindWith(obj, b)782}783784// BindJSON is a shortcut for c.MustBindWith(obj, binding.JSON).785func (c *Context) BindJSON(obj any) error {786 return c.MustBindWith(obj, binding.JSON)787}788789// BindXML is a shortcut for c.MustBindWith(obj, binding.XML).790func (c *Context) BindXML(obj any) error {791 return c.MustBindWith(obj, binding.XML)792}793794// BindQuery is a shortcut for c.MustBindWith(obj, binding.Query).795func (c *Context) BindQuery(obj any) error {796 return c.MustBindWith(obj, binding.Query)797}798799// BindYAML is a shortcut for c.MustBindWith(obj, binding.YAML).800func (c *Context) BindYAML(obj any) error {801 return c.MustBindWith(obj, binding.YAML)802}803804// BindTOML is a shortcut for c.MustBindWith(obj, binding.TOML).805func (c *Context) BindTOML(obj any) error {806 return c.MustBindWith(obj, binding.TOML)807}808809// BindPlain is a shortcut for c.MustBindWith(obj, binding.Plain).810func (c *Context) BindPlain(obj any) error {811 return c.MustBindWith(obj, binding.Plain)812}813814// BindHeader is a shortcut for c.MustBindWith(obj, binding.Header).815func (c *Context) BindHeader(obj any) error {816 return c.MustBindWith(obj, binding.Header)817}818819// BindUri binds the passed struct pointer using binding.Uri.820// It will abort the request with HTTP 400 if any error occurs.821func (c *Context) BindUri(obj any) error {822 if err := c.ShouldBindUri(obj); err != nil {823 c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) //nolint: errcheck824 return err825 }826 return nil827}828829// MustBindWith binds the passed struct pointer using the specified binding engine.830// It will abort the request with HTTP 400 if any error occurs.831// See the binding package.832func (c *Context) MustBindWith(obj any, b binding.Binding) error {833 err := c.ShouldBindWith(obj, b)834 if err != nil {835 var maxBytesErr *http.MaxBytesError836837 // Note: When using sonic or go-json as JSON encoder, they do not propagate the http.MaxBytesError error838 // https://github.com/goccy/go-json/issues/485839 // https://github.com/bytedance/sonic/issues/800840 switch {841 case errors.As(err, &maxBytesErr):842 c.AbortWithError(http.StatusRequestEntityTooLarge, err).SetType(ErrorTypeBind) //nolint: errcheck843 default:844 c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) //nolint: errcheck845 }846 return err847 }848 return nil849}850851// ShouldBind checks the Method and Content-Type to select a binding engine automatically,852// Depending on the "Content-Type" header different bindings are used, for example:853//854// "application/json" --> JSON binding855// "application/xml" --> XML binding856//857// It parses the request's body based on the Content-Type (e.g., JSON or XML).858// It decodes the payload into the struct specified as a pointer.859// Like c.Bind() but this method does not set the response status code to 400 or abort if input is not valid.860func (c *Context) ShouldBind(obj any) error {861 b := binding.Default(c.Request.Method, c.ContentType())862 return c.ShouldBindWith(obj, b)863}864865// ShouldBindJSON is a shortcut for c.ShouldBindWith(obj, binding.JSON).866//867// Example:868//869// POST /user870// Content-Type: application/json871//872// Request Body:873// {874// "name": "Manu",875// "age": 20876// }877//878// type User struct {879// Name string `json:"name"`880// Age int `json:"age"`881// }882//883// var user User884// if err := c.ShouldBindJSON(&user); err != nil {885// c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})886// return887// }888// c.JSON(http.StatusOK, user)889func (c *Context) ShouldBindJSON(obj any) error {890 return c.ShouldBindWith(obj, binding.JSON)891}892893// ShouldBindXML is a shortcut for c.ShouldBindWith(obj, binding.XML).894// It works like ShouldBindJSON but binds the request body as XML data.895func (c *Context) ShouldBindXML(obj any) error {896 return c.ShouldBindWith(obj, binding.XML)897}898899// ShouldBindQuery is a shortcut for c.ShouldBindWith(obj, binding.Query).900// It works like ShouldBindJSON but binds query parameters from the URL.901func (c *Context) ShouldBindQuery(obj any) error {902 return c.ShouldBindWith(obj, binding.Query)903}904905// ShouldBindYAML is a shortcut for c.ShouldBindWith(obj, binding.YAML).906// It works like ShouldBindJSON but binds the request body as YAML data.907func (c *Context) ShouldBindYAML(obj any) error {908 return c.ShouldBindWith(obj, binding.YAML)909}910911// ShouldBindTOML is a shortcut for c.ShouldBindWith(obj, binding.TOML).912// It works like ShouldBindJSON but binds the request body as TOML data.913func (c *Context) ShouldBindTOML(obj any) error {914 return c.ShouldBindWith(obj, binding.TOML)915}916917// ShouldBindPlain is a shortcut for c.ShouldBindWith(obj, binding.Plain).918// It works like ShouldBindJSON but binds plain text data from the request body.919func (c *Context) ShouldBindPlain(obj any) error {920 return c.ShouldBindWith(obj, binding.Plain)921}922923// ShouldBindHeader is a shortcut for c.ShouldBindWith(obj, binding.Header).924// It works like ShouldBindJSON but binds values from HTTP headers.925func (c *Context) ShouldBindHeader(obj any) error {926 return c.ShouldBindWith(obj, binding.Header)927}928929// ShouldBindUri binds the passed struct pointer using the specified binding engine.930// It works like ShouldBindJSON but binds parameters from the URI.931func (c *Context) ShouldBindUri(obj any) error {932 m := make(map[string][]string, len(c.Params))933 for _, v := range c.Params {934 m[v.Key] = []string{v.Value}935 }936 return binding.Uri.BindUri(m, obj)937}938939// ShouldBindWith binds the passed struct pointer using the specified binding engine.940// See the binding package.941func (c *Context) ShouldBindWith(obj any, b binding.Binding) error {942 return b.Bind(c.Request, obj)943}944945// ShouldBindBodyWith is similar with ShouldBindWith, but it stores the request946// body into the context, and reuse when it is called again.947//948// NOTE: This method reads the body before binding. So you should use949// ShouldBindWith for better performance if you need to call only once.950func (c *Context) ShouldBindBodyWith(obj any, bb binding.BindingBody) (err error) {951 var body []byte952 if cb, ok := c.Get(BodyBytesKey); ok {953 if cbb, ok := cb.([]byte); ok {954 body = cbb955 }956 }957 if body == nil {958 body, err = io.ReadAll(c.Request.Body)959 if err != nil {960 return err961 }962 c.Set(BodyBytesKey, body)963 }964 return bb.BindBody(body, obj)965}966967// ShouldBindBodyWithJSON is a shortcut for c.ShouldBindBodyWith(obj, binding.JSON).968func (c *Context) ShouldBindBodyWithJSON(obj any) error {969 return c.ShouldBindBodyWith(obj, binding.JSON)970}971972// ShouldBindBodyWithXML is a shortcut for c.ShouldBindBodyWith(obj, binding.XML).973func (c *Context) ShouldBindBodyWithXML(obj any) error {974 return c.ShouldBindBodyWith(obj, binding.XML)975}976977// ShouldBindBodyWithYAML is a shortcut for c.ShouldBindBodyWith(obj, binding.YAML).978func (c *Context) ShouldBindBodyWithYAML(obj any) error {979 return c.ShouldBindBodyWith(obj, binding.YAML)980}981982// ShouldBindBodyWithTOML is a shortcut for c.ShouldBindBodyWith(obj, binding.TOML).983func (c *Context) ShouldBindBodyWithTOML(obj any) error {984 return c.ShouldBindBodyWith(obj, binding.TOML)985}986987// ShouldBindBodyWithPlain is a shortcut for c.ShouldBindBodyWith(obj, binding.Plain).988func (c *Context) ShouldBindBodyWithPlain(obj any) error {989 return c.ShouldBindBodyWith(obj, binding.Plain)990}991992// ClientIP implements one best effort algorithm to return the real client IP.993// It calls c.RemoteIP() under the hood, to check if the remote IP is a trusted proxy or not.994// If it is it will then try to parse the headers defined in Engine.RemoteIPHeaders (defaulting to [X-Forwarded-For, X-Real-IP]).995// If the headers are not syntactically valid OR the remote IP does not correspond to a trusted proxy,996// the remote IP (coming from Request.RemoteAddr) is returned.997func (c *Context) ClientIP() string {998 // Check if we're running on a trusted platform, continue running backwards if error999 if c.engine.TrustedPlatform != "" {1000 // Developers can define their own header of Trusted Platform or use predefined constants1001 if addr := c.requestHeader(c.engine.TrustedPlatform); addr != "" {1002 return addr1003 }1004 }10051006 // Legacy "AppEngine" flag1007 if c.engine.AppEngine {1008 log.Println(`The AppEngine flag is going to be deprecated. Please check issues #2723 and #2739 and use 'TrustedPlatform: gin.PlatformGoogleAppEngine' instead.`)1009 if addr := c.requestHeader("X-Appengine-Remote-Addr"); addr != "" {1010 return addr1011 }1012 }10131014 var (1015 trusted bool1016 remoteIP net.IP1017 )1018 // If gin is listening a unix socket, always trust it.1019 localAddr, ok := c.Request.Context().Value(http.LocalAddrContextKey).(net.Addr)1020 if ok && strings.HasPrefix(localAddr.Network(), "unix") {1021 trusted = true1022 }10231024 // Fallback1025 if !trusted {1026 // It also checks if the remoteIP is a trusted proxy or not.1027 // In order to perform this validation, it will see if the IP is contained within at least one of the CIDR blocks1028 // defined by Engine.SetTrustedProxies()1029 remoteIP = net.ParseIP(c.RemoteIP())1030 if remoteIP == nil {1031 return ""1032 }1033 trusted = c.engine.isTrustedProxy(remoteIP)1034 }10351036 if trusted && c.engine.ForwardedByClientIP && c.engine.RemoteIPHeaders != nil {1037 for _, headerName := range c.engine.RemoteIPHeaders {1038 headerValue := strings.Join(c.Request.Header.Values(headerName), ",")1039 ip, valid := c.engine.validateHeader(headerValue)1040 if valid {1041 return ip1042 }1043 }1044 }1045 return remoteIP.String()1046}10471048// RemoteIP parses the IP from Request.RemoteAddr, normalizes and returns the IP (without the port).1049func (c *Context) RemoteIP() string {1050 ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr))1051 if err != nil {1052 return ""1053 }1054 return ip1055}10561057// ContentType returns the Content-Type header of the request.1058func (c *Context) ContentType() string {1059 return filterFlags(c.requestHeader("Content-Type"))1060}10611062// IsWebsocket returns true if the request headers indicate that a websocket1063// handshake is being initiated by the client.1064func (c *Context) IsWebsocket() bool {1065 if strings.Contains(strings.ToLower(c.requestHeader("Connection")), "upgrade") &&1066 strings.EqualFold(c.requestHeader("Upgrade"), "websocket") {1067 return true1068 }1069 return false1070}10711072// Scheme returns the HTTP scheme of the request ("http" or "https").1073// When running behind reverse proxies or load balancers `Request.URL.Scheme` is usually empty.1074// the original scheme is commonly forwarded via headers such as X-Forwarded-Proto.1075// Reference:1076// https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Forwarded-Proto1077func (c *Context) Scheme() string {1078 if c.Request.TLS != nil {1079 return "https"1080 }1081 if scheme := c.requestHeader("X-Forwarded-Proto"); scheme != "" {1082 return scheme1083 }1084 if scheme := c.requestHeader("X-Forwarded-Protocol"); scheme != "" {1085 return scheme1086 }1087 if ssl := c.requestHeader("X-Forwarded-Ssl"); ssl == "on" {1088 return "https"1089 }1090 if scheme := c.requestHeader("X-Url-Scheme"); scheme != "" {1091 return scheme1092 }1093 if scheme := c.Request.URL.Scheme; scheme != "" {1094 return scheme1095 }1096 return "http"1097}10981099func (c *Context) requestHeader(key string) string {1100 return c.Request.Header.Get(key)1101}11021103/************************************/1104/******** RESPONSE RENDERING ********/1105/************************************/11061107// bodyAllowedForStatus is a copy of http.bodyAllowedForStatus non-exported function.1108// Uses http.StatusContinue constant for better code clarity.1109func bodyAllowedForStatus(status int) bool {1110 switch {1111 case status >= http.StatusContinue && status < http.StatusOK:1112 return false1113 case status == http.StatusNoContent:1114 return false1115 case status == http.StatusNotModified:1116 return false1117 }1118 return true1119}11201121// Status sets the HTTP response code.1122func (c *Context) Status(code int) {1123 c.Writer.WriteHeader(code)1124}11251126// Header is an intelligent shortcut for c.Writer.Header().Set(key, value).1127// It writes a header in the response.1128// If value == "", this method removes the header `c.Writer.Header().Del(key)`1129func (c *Context) Header(key, value string) {1130 if value == "" {1131 c.Writer.Header().Del(key)1132 return1133 }1134 c.Writer.Header().Set(key, value)1135}11361137// GetHeader returns value from request headers.1138func (c *Context) GetHeader(key string) string {1139 return c.requestHeader(key)1140}11411142// GetRawData returns stream data.1143func (c *Context) GetRawData() ([]byte, error) {1144 if c.Request.Body == nil {1145 return nil, errors.New("cannot read nil body")1146 }1147 return io.ReadAll(c.Request.Body)1148}11491150// SetSameSite with cookie1151func (c *Context) SetSameSite(samesite http.SameSite) {1152 c.sameSite = samesite1153}11541155// SetCookie adds a Set-Cookie header to the ResponseWriter's headers.1156// The provided cookie must have a valid Name. Invalid cookies may be1157// silently dropped.1158func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool) {1159 if path == "" {1160 path = "/"1161 }1162 http.SetCookie(c.Writer, &http.Cookie{1163 Name: name,1164 Value: url.QueryEscape(value),1165 MaxAge: maxAge,1166 Path: path,1167 Domain: domain,1168 SameSite: c.sameSite,1169 Secure: secure,1170 HttpOnly: httpOnly,1171 })1172}11731174// SetCookieData adds a Set-Cookie header to the ResponseWriter's headers.1175// It accepts a pointer to http.Cookie structure for more flexibility in setting cookie attributes.1176// The provided cookie must have a valid Name. Invalid cookies may be silently dropped.1177func (c *Context) SetCookieData(cookie *http.Cookie) {1178 if cookie.Path == "" {1179 cookie.Path = "/"1180 }1181 if cookie.SameSite == http.SameSiteDefaultMode {1182 cookie.SameSite = c.sameSite1183 }1184 http.SetCookie(c.Writer, cookie)1185}11861187// Cookie returns the named cookie provided in the request or1188// ErrNoCookie if not found. And return the named cookie is unescaped.1189// If multiple cookies match the given name, only one cookie will1190// be returned.1191func (c *Context) Cookie(name string) (string, error) {1192 cookie, err := c.Request.Cookie(name)1193 if err != nil {1194 return "", err1195 }1196 val, _ := url.QueryUnescape(cookie.Value)1197 return val, nil1198}11991200// Render writes the response headers and calls render.Render to render data.1201func (c *Context) Render(code int, r render.Render) {1202 c.Status(code)12031204 if !bodyAllowedForStatus(code) {1205 r.WriteContentType(c.Writer)1206 c.Writer.WriteHeaderNow()1207 return1208 }12091210 if err := r.Render(c.Writer); err != nil {1211 // Pushing error to c.Errors1212 _ = c.Error(err)1213 c.Abort()1214 }1215}12161217// HTML renders the HTTP template specified by its file name.1218// It also updates the HTTP code and sets the Content-Type as "text/html".1219// See http://golang.org/doc/articles/wiki/1220func (c *Context) HTML(code int, name string, obj any) {1221 if c.engine.HTMLRender == nil {1222 c.Render(code, render.HTML{})1223 return1224 }12251226 instance := c.engine.HTMLRender.Instance(name, obj)1227 c.Render(code, instance)1228}12291230// IndentedJSON serializes the given struct as pretty JSON (indented + endlines) into the response body.1231// It also sets the Content-Type as "application/json".1232// WARNING: we recommend using this only for development purposes since printing pretty JSON is1233// more CPU and bandwidth consuming. Use Context.JSON() instead.1234func (c *Context) IndentedJSON(code int, obj any) {1235 c.Render(code, render.IndentedJSON{Data: obj})1236}12371238// SecureJSON serializes the given struct as Secure JSON into the response body.1239// Default prepends "while(1);" to response body if the given struct is array values.1240// It also sets the Content-Type as "application/json".1241func (c *Context) SecureJSON(code int, obj any) {1242 c.Render(code, render.SecureJSON{Prefix: c.engine.secureJSONPrefix, Data: obj})1243}12441245// JSONP serializes the given struct as JSON into the response body.1246// It adds padding to response body to request data from a server residing in a different domain than the client.1247// It also sets the Content-Type as "application/javascript".1248func (c *Context) JSONP(code int, obj any) {1249 callback := c.DefaultQuery("callback", "")1250 if callback == "" {1251 c.Render(code, render.JSON{Data: obj})1252 return1253 }1254 c.Render(code, render.JsonpJSON{Callback: callback, Data: obj})1255}12561257// JSON serializes the given struct as JSON into the response body.1258// It also sets the Content-Type as "application/json".1259func (c *Context) JSON(code int, obj any) {1260 c.Render(code, render.JSON{Data: obj})1261}12621263// AsciiJSON serializes the given struct as JSON into the response body with unicode to ASCII string.1264// It also sets the Content-Type as "application/json".1265func (c *Context) AsciiJSON(code int, obj any) {1266 c.Render(code, render.AsciiJSON{Data: obj})1267}12681269// PureJSON serializes the given struct as JSON into the response body.1270// PureJSON, unlike JSON, does not replace special html characters with their unicode entities.1271func (c *Context) PureJSON(code int, obj any) {1272 c.Render(code, render.PureJSON{Data: obj})1273}12741275// XML serializes the given struct as XML into the response body.1276// It also sets the Content-Type as "application/xml".1277func (c *Context) XML(code int, obj any) {1278 c.Render(code, render.XML{Data: obj})1279}12801281// PDF writes the given PDF binary data into the response body.1282// It also sets the Content-Type as "application/pdf".1283func (c *Context) PDF(code int, data []byte) {1284 c.Render(code, render.PDF{Data: data})1285}12861287// YAML serializes the given struct as YAML into the response body.1288func (c *Context) YAML(code int, obj any) {1289 c.Render(code, render.YAML{Data: obj})1290}12911292// TOML serializes the given struct as TOML into the response body.1293func (c *Context) TOML(code int, obj any) {1294 c.Render(code, render.TOML{Data: obj})1295}12961297// ProtoBuf serializes the given struct as ProtoBuf into the response body.1298func (c *Context) ProtoBuf(code int, obj any) {1299 c.Render(code, render.ProtoBuf{Data: obj})1300}13011302// BSON serializes the given struct as BSON into the response body.1303func (c *Context) BSON(code int, obj any) {1304 c.Render(code, render.BSON{Data: obj})1305}13061307// String writes the given string into the response body.1308func (c *Context) String(code int, format string, values ...any) {1309 c.Render(code, render.String{Format: format, Data: values})1310}13111312// Redirect returns an HTTP redirect to the specific location.1313func (c *Context) Redirect(code int, location string) {1314 c.Render(-1, render.Redirect{1315 Code: code,1316 Location: location,1317 Request: c.Request,1318 })1319}13201321// Data writes some data into the body stream and updates the HTTP code.1322func (c *Context) Data(code int, contentType string, data []byte) {1323 c.Render(code, render.Data{1324 ContentType: contentType,1325 Data: data,1326 })1327}13281329// DataFromReader writes the specified reader into the body stream and updates the HTTP code.1330func (c *Context) DataFromReader(code int, contentLength int64, contentType string, reader io.Reader, extraHeaders map[string]string) {1331 c.Render(code, render.Reader{1332 Headers: extraHeaders,1333 ContentType: contentType,1334 ContentLength: contentLength,1335 Reader: reader,1336 })1337}13381339// File writes the specified file into the body stream in an efficient way.1340func (c *Context) File(filepath string) {1341 http.ServeFile(c.Writer, c.Request, filepath)1342}13431344// FileFromFS writes the specified file from http.FileSystem into the body stream in an efficient way.1345func (c *Context) FileFromFS(filepath string, fs http.FileSystem) {1346 defer func(old string) {1347 c.Request.URL.Path = old1348 }(c.Request.URL.Path)13491350 c.Request.URL.Path = filepath13511352 http.FileServer(fs).ServeHTTP(c.Writer, c.Request)1353}13541355var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")13561357func escapeQuotes(s string) string {1358 return quoteEscaper.Replace(s)1359}13601361// FileAttachment writes the specified file into the body stream in an efficient way1362// On the client side, the file will typically be downloaded with the given filename1363func (c *Context) FileAttachment(filepath, filename string) {1364 if isASCII(filename) {1365 c.Writer.Header().Set("Content-Disposition", `attachment; filename="`+escapeQuotes(filename)+`"`)1366 } else {1367 c.Writer.Header().Set("Content-Disposition", `attachment; filename*=UTF-8''`+url.QueryEscape(filename))1368 }1369 http.ServeFile(c.Writer, c.Request, filepath)1370}13711372// SSEvent writes a Server-Sent Event into the body stream.1373func (c *Context) SSEvent(name string, message any) {1374 c.Render(-1, sse.Event{1375 Event: name,1376 Data: message,1377 })1378}13791380// Stream sends a streaming response and returns a boolean1381// indicates "Is client disconnected in middle of stream"1382func (c *Context) Stream(step func(w io.Writer) bool) bool {1383 w := c.Writer1384 clientGone := w.CloseNotify()1385 for {1386 select {1387 case <-clientGone:1388 return true1389 default:1390 keepOpen := step(w)1391 w.Flush()1392 if !keepOpen {1393 return false1394 }1395 }1396 }1397}13981399/************************************/1400/******** CONTENT NEGOTIATION *******/1401/************************************/14021403// Negotiate contains all negotiations data.1404type Negotiate struct {1405 Offered []string1406 HTMLName string1407 HTMLData any1408 JSONData any1409 XMLData any1410 YAMLData any1411 Data any1412 TOMLData any1413 PROTOBUFData any1414 BSONData any1415}14161417// Negotiate calls different Render according to acceptable Accept format.1418func (c *Context) Negotiate(code int, config Negotiate) {1419 switch c.NegotiateFormat(config.Offered...) {1420 case binding.MIMEJSON:1421 data := chooseData(config.JSONData, config.Data)1422 c.JSON(code, data)14231424 case binding.MIMEHTML:1425 data := chooseData(config.HTMLData, config.Data)1426 c.HTML(code, config.HTMLName, data)14271428 case binding.MIMEXML:1429 data := chooseData(config.XMLData, config.Data)1430 c.XML(code, data)14311432 case binding.MIMEYAML, binding.MIMEYAML2:1433 data := chooseData(config.YAMLData, config.Data)1434 c.YAML(code, data)14351436 case binding.MIMETOML:1437 data := chooseData(config.TOMLData, config.Data)1438 c.TOML(code, data)14391440 case binding.MIMEPROTOBUF:1441 data := chooseData(config.PROTOBUFData, config.Data)1442 c.ProtoBuf(code, data)14431444 case binding.MIMEBSON:1445 data := chooseData(config.BSONData, config.Data)1446 c.BSON(code, data)14471448 default:1449 c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server")) //nolint: errcheck1450 }1451}14521453// NegotiateFormat returns an acceptable Accept format.1454func (c *Context) NegotiateFormat(offered ...string) string {1455 assert1(len(offered) > 0, "you must provide at least one offer")14561457 if c.Accepted == nil {1458 c.Accepted = parseAccept(c.requestHeader("Accept"))1459 }1460 if len(c.Accepted) == 0 {1461 return offered[0]1462 }1463 for _, accepted := range c.Accepted {1464 for _, offer := range offered {1465 // According to RFC 2616 and RFC 2396, non-ASCII characters are not allowed in headers,1466 // therefore we can just iterate over the string without casting it into []rune1467 i := 01468 for ; i < len(accepted) && i < len(offer); i++ {1469 if accepted[i] == '*' || offer[i] == '*' {1470 return offer1471 }1472 if accepted[i] != offer[i] {1473 break1474 }1475 }1476 if i == len(accepted) {1477 return offer1478 }1479 }1480 }1481 return ""1482}14831484// SetAccepted sets Accept header data.1485func (c *Context) SetAccepted(formats ...string) {1486 c.Accepted = formats1487}14881489/************************************/1490/***** GOLANG.ORG/X/NET/CONTEXT *****/1491/************************************/14921493// hasRequestContext returns whether c.Request has Context and fallback.1494func (c *Context) hasRequestContext() bool {1495 hasFallback := c.engine != nil && c.engine.ContextWithFallback1496 hasRequestContext := c.Request != nil && c.Request.Context() != nil1497 return hasFallback && hasRequestContext1498}14991500// Deadline returns that there is no deadline (ok==false) when c.Request has no Context.1501func (c *Context) Deadline() (deadline time.Time, ok bool) {1502 if !c.hasRequestContext() {1503 return1504 }1505 return c.Request.Context().Deadline()1506}15071508// Done returns nil (chan which will wait forever) when c.Request has no Context.1509func (c *Context) Done() <-chan struct{} {1510 if !c.hasRequestContext() {1511 return nil1512 }1513 return c.Request.Context().Done()1514}15151516// Err returns nil when c.Request has no Context.1517func (c *Context) Err() error {1518 if !c.hasRequestContext() {1519 return nil1520 }1521 return c.Request.Context().Err()1522}15231524// Value returns the value associated with this context for key, or nil1525// if no value is associated with key. Successive calls to Value with1526// the same key returns the same result.1527func (c *Context) Value(key any) any {1528 if key == ContextRequestKey {1529 return c.Request1530 }1531 if key == ContextKey {1532 return c1533 }1534 if keyAsString, ok := key.(string); ok {1535 if val, exists := c.Get(keyAsString); exists {1536 return val1537 }1538 }1539 if !c.hasRequestContext() {1540 return nil1541 }1542 return c.Request.Context().Value(key)1543}