podman
1233 строки · 37.1 Кб
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
5package gin
6
7import (
8"errors"
9"io"
10"log"
11"math"
12"mime/multipart"
13"net"
14"net/http"
15"net/url"
16"os"
17"path/filepath"
18"strings"
19"sync"
20"time"
21
22"github.com/gin-contrib/sse"
23"github.com/gin-gonic/gin/binding"
24"github.com/gin-gonic/gin/render"
25)
26
27// Content-Type MIME of the most common data formats.
28const (
29MIMEJSON = binding.MIMEJSON
30MIMEHTML = binding.MIMEHTML
31MIMEXML = binding.MIMEXML
32MIMEXML2 = binding.MIMEXML2
33MIMEPlain = binding.MIMEPlain
34MIMEPOSTForm = binding.MIMEPOSTForm
35MIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm
36MIMEYAML = binding.MIMEYAML
37MIMETOML = binding.MIMETOML
38)
39
40// BodyBytesKey indicates a default body bytes key.
41const BodyBytesKey = "_gin-gonic/gin/bodybyteskey"
42
43// ContextKey is the key that a Context returns itself for.
44const ContextKey = "_gin-gonic/gin/contextkey"
45
46// abortIndex represents a typical value used in abort functions.
47const abortIndex int8 = math.MaxInt8 >> 1
48
49// Context is the most important part of gin. It allows us to pass variables between middleware,
50// manage the flow, validate the JSON of a request and render a JSON response for example.
51type Context struct {
52writermem responseWriter
53Request *http.Request
54Writer ResponseWriter
55
56Params Params
57handlers HandlersChain
58index int8
59fullPath string
60
61engine *Engine
62params *Params
63skippedNodes *[]skippedNode
64
65// This mutex protects Keys map.
66mu sync.RWMutex
67
68// Keys is a key/value pair exclusively for the context of each request.
69Keys map[string]any
70
71// Errors is a list of errors attached to all the handlers/middlewares who used this context.
72Errors errorMsgs
73
74// Accepted defines a list of manually accepted formats for content negotiation.
75Accepted []string
76
77// queryCache caches the query result from c.Request.URL.Query().
78queryCache url.Values
79
80// formCache caches c.Request.PostForm, which contains the parsed form data from POST, PATCH,
81// or PUT body parameters.
82formCache url.Values
83
84// SameSite allows a server to define a cookie attribute making it impossible for
85// the browser to send this cookie along with cross-site requests.
86sameSite http.SameSite
87}
88
89/************************************/
90/********** CONTEXT CREATION ********/
91/************************************/
92
93func (c *Context) reset() {
94c.Writer = &c.writermem
95c.Params = c.Params[:0]
96c.handlers = nil
97c.index = -1
98
99c.fullPath = ""
100c.Keys = nil
101c.Errors = c.Errors[:0]
102c.Accepted = nil
103c.queryCache = nil
104c.formCache = nil
105c.sameSite = 0
106*c.params = (*c.params)[:0]
107*c.skippedNodes = (*c.skippedNodes)[:0]
108}
109
110// Copy returns a copy of the current context that can be safely used outside the request's scope.
111// This has to be used when the context has to be passed to a goroutine.
112func (c *Context) Copy() *Context {
113cp := Context{
114writermem: c.writermem,
115Request: c.Request,
116Params: c.Params,
117engine: c.engine,
118}
119cp.writermem.ResponseWriter = nil
120cp.Writer = &cp.writermem
121cp.index = abortIndex
122cp.handlers = nil
123cp.Keys = map[string]any{}
124for k, v := range c.Keys {
125cp.Keys[k] = v
126}
127paramCopy := make([]Param, len(cp.Params))
128copy(paramCopy, cp.Params)
129cp.Params = paramCopy
130return &cp
131}
132
133// HandlerName returns the main handler's name. For example if the handler is "handleGetUsers()",
134// this function will return "main.handleGetUsers".
135func (c *Context) HandlerName() string {
136return nameOfFunction(c.handlers.Last())
137}
138
139// HandlerNames returns a list of all registered handlers for this context in descending order,
140// following the semantics of HandlerName()
141func (c *Context) HandlerNames() []string {
142hn := make([]string, 0, len(c.handlers))
143for _, val := range c.handlers {
144hn = append(hn, nameOfFunction(val))
145}
146return hn
147}
148
149// Handler returns the main handler.
150func (c *Context) Handler() HandlerFunc {
151return c.handlers.Last()
152}
153
154// FullPath returns a matched route full path. For not found routes
155// returns an empty string.
156//
157// router.GET("/user/:id", func(c *gin.Context) {
158// c.FullPath() == "/user/:id" // true
159// })
160func (c *Context) FullPath() string {
161return c.fullPath
162}
163
164/************************************/
165/*********** FLOW CONTROL ***********/
166/************************************/
167
168// Next should be used only inside middleware.
169// It executes the pending handlers in the chain inside the calling handler.
170// See example in GitHub.
171func (c *Context) Next() {
172c.index++
173for c.index < int8(len(c.handlers)) {
174c.handlers[c.index](c)
175c.index++
176}
177}
178
179// IsAborted returns true if the current context was aborted.
180func (c *Context) IsAborted() bool {
181return c.index >= abortIndex
182}
183
184// Abort prevents pending handlers from being called. Note that this will not stop the current handler.
185// Let's say you have an authorization middleware that validates that the current request is authorized.
186// If the authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers
187// for this request are not called.
188func (c *Context) Abort() {
189c.index = abortIndex
190}
191
192// AbortWithStatus calls `Abort()` and writes the headers with the specified status code.
193// For example, a failed attempt to authenticate a request could use: context.AbortWithStatus(401).
194func (c *Context) AbortWithStatus(code int) {
195c.Status(code)
196c.Writer.WriteHeaderNow()
197c.Abort()
198}
199
200// AbortWithStatusJSON calls `Abort()` and then `JSON` internally.
201// This method stops the chain, writes the status code and return a JSON body.
202// It also sets the Content-Type as "application/json".
203func (c *Context) AbortWithStatusJSON(code int, jsonObj any) {
204c.Abort()
205c.JSON(code, jsonObj)
206}
207
208// AbortWithError calls `AbortWithStatus()` and `Error()` internally.
209// This method stops the chain, writes the status code and pushes the specified error to `c.Errors`.
210// See Context.Error() for more details.
211func (c *Context) AbortWithError(code int, err error) *Error {
212c.AbortWithStatus(code)
213return c.Error(err)
214}
215
216/************************************/
217/********* ERROR MANAGEMENT *********/
218/************************************/
219
220// Error attaches an error to the current context. The error is pushed to a list of errors.
221// It's a good idea to call Error for each error that occurred during the resolution of a request.
222// A middleware can be used to collect all the errors and push them to a database together,
223// print a log, or append it in the HTTP response.
224// Error will panic if err is nil.
225func (c *Context) Error(err error) *Error {
226if err == nil {
227panic("err is nil")
228}
229
230var parsedError *Error
231ok := errors.As(err, &parsedError)
232if !ok {
233parsedError = &Error{
234Err: err,
235Type: ErrorTypePrivate,
236}
237}
238
239c.Errors = append(c.Errors, parsedError)
240return parsedError
241}
242
243/************************************/
244/******** METADATA MANAGEMENT********/
245/************************************/
246
247// Set is used to store a new key/value pair exclusively for this context.
248// It also lazy initializes c.Keys if it was not used previously.
249func (c *Context) Set(key string, value any) {
250c.mu.Lock()
251defer c.mu.Unlock()
252if c.Keys == nil {
253c.Keys = make(map[string]any)
254}
255
256c.Keys[key] = value
257}
258
259// Get returns the value for the given key, ie: (value, true).
260// If the value does not exist it returns (nil, false)
261func (c *Context) Get(key string) (value any, exists bool) {
262c.mu.RLock()
263defer c.mu.RUnlock()
264value, exists = c.Keys[key]
265return
266}
267
268// MustGet returns the value for the given key if it exists, otherwise it panics.
269func (c *Context) MustGet(key string) any {
270if value, exists := c.Get(key); exists {
271return value
272}
273panic("Key \"" + key + "\" does not exist")
274}
275
276// GetString returns the value associated with the key as a string.
277func (c *Context) GetString(key string) (s string) {
278if val, ok := c.Get(key); ok && val != nil {
279s, _ = val.(string)
280}
281return
282}
283
284// GetBool returns the value associated with the key as a boolean.
285func (c *Context) GetBool(key string) (b bool) {
286if val, ok := c.Get(key); ok && val != nil {
287b, _ = val.(bool)
288}
289return
290}
291
292// GetInt returns the value associated with the key as an integer.
293func (c *Context) GetInt(key string) (i int) {
294if val, ok := c.Get(key); ok && val != nil {
295i, _ = val.(int)
296}
297return
298}
299
300// GetInt64 returns the value associated with the key as an integer.
301func (c *Context) GetInt64(key string) (i64 int64) {
302if val, ok := c.Get(key); ok && val != nil {
303i64, _ = val.(int64)
304}
305return
306}
307
308// GetUint returns the value associated with the key as an unsigned integer.
309func (c *Context) GetUint(key string) (ui uint) {
310if val, ok := c.Get(key); ok && val != nil {
311ui, _ = val.(uint)
312}
313return
314}
315
316// GetUint64 returns the value associated with the key as an unsigned integer.
317func (c *Context) GetUint64(key string) (ui64 uint64) {
318if val, ok := c.Get(key); ok && val != nil {
319ui64, _ = val.(uint64)
320}
321return
322}
323
324// GetFloat64 returns the value associated with the key as a float64.
325func (c *Context) GetFloat64(key string) (f64 float64) {
326if val, ok := c.Get(key); ok && val != nil {
327f64, _ = val.(float64)
328}
329return
330}
331
332// GetTime returns the value associated with the key as time.
333func (c *Context) GetTime(key string) (t time.Time) {
334if val, ok := c.Get(key); ok && val != nil {
335t, _ = val.(time.Time)
336}
337return
338}
339
340// GetDuration returns the value associated with the key as a duration.
341func (c *Context) GetDuration(key string) (d time.Duration) {
342if val, ok := c.Get(key); ok && val != nil {
343d, _ = val.(time.Duration)
344}
345return
346}
347
348// GetStringSlice returns the value associated with the key as a slice of strings.
349func (c *Context) GetStringSlice(key string) (ss []string) {
350if val, ok := c.Get(key); ok && val != nil {
351ss, _ = val.([]string)
352}
353return
354}
355
356// GetStringMap returns the value associated with the key as a map of interfaces.
357func (c *Context) GetStringMap(key string) (sm map[string]any) {
358if val, ok := c.Get(key); ok && val != nil {
359sm, _ = val.(map[string]any)
360}
361return
362}
363
364// GetStringMapString returns the value associated with the key as a map of strings.
365func (c *Context) GetStringMapString(key string) (sms map[string]string) {
366if val, ok := c.Get(key); ok && val != nil {
367sms, _ = val.(map[string]string)
368}
369return
370}
371
372// GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.
373func (c *Context) GetStringMapStringSlice(key string) (smss map[string][]string) {
374if val, ok := c.Get(key); ok && val != nil {
375smss, _ = val.(map[string][]string)
376}
377return
378}
379
380/************************************/
381/************ INPUT DATA ************/
382/************************************/
383
384// Param returns the value of the URL param.
385// It is a shortcut for c.Params.ByName(key)
386//
387// router.GET("/user/:id", func(c *gin.Context) {
388// // a GET request to /user/john
389// id := c.Param("id") // id == "/john"
390// // a GET request to /user/john/
391// id := c.Param("id") // id == "/john/"
392// })
393func (c *Context) Param(key string) string {
394return c.Params.ByName(key)
395}
396
397// AddParam adds param to context and
398// replaces path param key with given value for e2e testing purposes
399// Example Route: "/user/:id"
400// AddParam("id", 1)
401// Result: "/user/1"
402func (c *Context) AddParam(key, value string) {
403c.Params = append(c.Params, Param{Key: key, Value: value})
404}
405
406// Query returns the keyed url query value if it exists,
407// otherwise it returns an empty string `("")`.
408// It is shortcut for `c.Request.URL.Query().Get(key)`
409//
410// GET /path?id=1234&name=Manu&value=
411// c.Query("id") == "1234"
412// c.Query("name") == "Manu"
413// c.Query("value") == ""
414// c.Query("wtf") == ""
415func (c *Context) Query(key string) (value string) {
416value, _ = c.GetQuery(key)
417return
418}
419
420// DefaultQuery returns the keyed url query value if it exists,
421// otherwise it returns the specified defaultValue string.
422// See: Query() and GetQuery() for further information.
423//
424// GET /?name=Manu&lastname=
425// c.DefaultQuery("name", "unknown") == "Manu"
426// c.DefaultQuery("id", "none") == "none"
427// c.DefaultQuery("lastname", "none") == ""
428func (c *Context) DefaultQuery(key, defaultValue string) string {
429if value, ok := c.GetQuery(key); ok {
430return value
431}
432return defaultValue
433}
434
435// GetQuery is like Query(), it returns the keyed url query value
436// if it exists `(value, true)` (even when the value is an empty string),
437// otherwise it returns `("", false)`.
438// It is shortcut for `c.Request.URL.Query().Get(key)`
439//
440// GET /?name=Manu&lastname=
441// ("Manu", true) == c.GetQuery("name")
442// ("", false) == c.GetQuery("id")
443// ("", true) == c.GetQuery("lastname")
444func (c *Context) GetQuery(key string) (string, bool) {
445if values, ok := c.GetQueryArray(key); ok {
446return values[0], ok
447}
448return "", false
449}
450
451// QueryArray returns a slice of strings for a given query key.
452// The length of the slice depends on the number of params with the given key.
453func (c *Context) QueryArray(key string) (values []string) {
454values, _ = c.GetQueryArray(key)
455return
456}
457
458func (c *Context) initQueryCache() {
459if c.queryCache == nil {
460if c.Request != nil {
461c.queryCache = c.Request.URL.Query()
462} else {
463c.queryCache = url.Values{}
464}
465}
466}
467
468// GetQueryArray returns a slice of strings for a given query key, plus
469// a boolean value whether at least one value exists for the given key.
470func (c *Context) GetQueryArray(key string) (values []string, ok bool) {
471c.initQueryCache()
472values, ok = c.queryCache[key]
473return
474}
475
476// QueryMap returns a map for a given query key.
477func (c *Context) QueryMap(key string) (dicts map[string]string) {
478dicts, _ = c.GetQueryMap(key)
479return
480}
481
482// GetQueryMap returns a map for a given query key, plus a boolean value
483// whether at least one value exists for the given key.
484func (c *Context) GetQueryMap(key string) (map[string]string, bool) {
485c.initQueryCache()
486return c.get(c.queryCache, key)
487}
488
489// PostForm returns the specified key from a POST urlencoded form or multipart form
490// when it exists, otherwise it returns an empty string `("")`.
491func (c *Context) PostForm(key string) (value string) {
492value, _ = c.GetPostForm(key)
493return
494}
495
496// DefaultPostForm returns the specified key from a POST urlencoded form or multipart form
497// when it exists, otherwise it returns the specified defaultValue string.
498// See: PostForm() and GetPostForm() for further information.
499func (c *Context) DefaultPostForm(key, defaultValue string) string {
500if value, ok := c.GetPostForm(key); ok {
501return value
502}
503return defaultValue
504}
505
506// GetPostForm is like PostForm(key). It returns the specified key from a POST urlencoded
507// form or multipart form when it exists `(value, true)` (even when the value is an empty string),
508// otherwise it returns ("", false).
509// For example, during a PATCH request to update the user's email:
510//
511// email=mail@example.com --> ("mail@example.com", true) := GetPostForm("email") // set email to "mail@example.com"
512// email= --> ("", true) := GetPostForm("email") // set email to ""
513// --> ("", false) := GetPostForm("email") // do nothing with email
514func (c *Context) GetPostForm(key string) (string, bool) {
515if values, ok := c.GetPostFormArray(key); ok {
516return values[0], ok
517}
518return "", false
519}
520
521// PostFormArray returns a slice of strings for a given form key.
522// The length of the slice depends on the number of params with the given key.
523func (c *Context) PostFormArray(key string) (values []string) {
524values, _ = c.GetPostFormArray(key)
525return
526}
527
528func (c *Context) initFormCache() {
529if c.formCache == nil {
530c.formCache = make(url.Values)
531req := c.Request
532if err := req.ParseMultipartForm(c.engine.MaxMultipartMemory); err != nil {
533if !errors.Is(err, http.ErrNotMultipart) {
534debugPrint("error on parse multipart form array: %v", err)
535}
536}
537c.formCache = req.PostForm
538}
539}
540
541// GetPostFormArray returns a slice of strings for a given form key, plus
542// a boolean value whether at least one value exists for the given key.
543func (c *Context) GetPostFormArray(key string) (values []string, ok bool) {
544c.initFormCache()
545values, ok = c.formCache[key]
546return
547}
548
549// PostFormMap returns a map for a given form key.
550func (c *Context) PostFormMap(key string) (dicts map[string]string) {
551dicts, _ = c.GetPostFormMap(key)
552return
553}
554
555// GetPostFormMap returns a map for a given form key, plus a boolean value
556// whether at least one value exists for the given key.
557func (c *Context) GetPostFormMap(key string) (map[string]string, bool) {
558c.initFormCache()
559return c.get(c.formCache, key)
560}
561
562// get is an internal method and returns a map which satisfies conditions.
563func (c *Context) get(m map[string][]string, key string) (map[string]string, bool) {
564dicts := make(map[string]string)
565exist := false
566for k, v := range m {
567if i := strings.IndexByte(k, '['); i >= 1 && k[0:i] == key {
568if j := strings.IndexByte(k[i+1:], ']'); j >= 1 {
569exist = true
570dicts[k[i+1:][:j]] = v[0]
571}
572}
573}
574return dicts, exist
575}
576
577// FormFile returns the first file for the provided form key.
578func (c *Context) FormFile(name string) (*multipart.FileHeader, error) {
579if c.Request.MultipartForm == nil {
580if err := c.Request.ParseMultipartForm(c.engine.MaxMultipartMemory); err != nil {
581return nil, err
582}
583}
584f, fh, err := c.Request.FormFile(name)
585if err != nil {
586return nil, err
587}
588f.Close()
589return fh, err
590}
591
592// MultipartForm is the parsed multipart form, including file uploads.
593func (c *Context) MultipartForm() (*multipart.Form, error) {
594err := c.Request.ParseMultipartForm(c.engine.MaxMultipartMemory)
595return c.Request.MultipartForm, err
596}
597
598// SaveUploadedFile uploads the form file to specific dst.
599func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error {
600src, err := file.Open()
601if err != nil {
602return err
603}
604defer src.Close()
605
606if err = os.MkdirAll(filepath.Dir(dst), 0750); err != nil {
607return err
608}
609
610out, err := os.Create(dst)
611if err != nil {
612return err
613}
614defer out.Close()
615
616_, err = io.Copy(out, src)
617return err
618}
619
620// Bind checks the Method and Content-Type to select a binding engine automatically,
621// Depending on the "Content-Type" header different bindings are used, for example:
622//
623// "application/json" --> JSON binding
624// "application/xml" --> XML binding
625//
626// It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input.
627// It decodes the json payload into the struct specified as a pointer.
628// It writes a 400 error and sets Content-Type header "text/plain" in the response if input is not valid.
629func (c *Context) Bind(obj any) error {
630b := binding.Default(c.Request.Method, c.ContentType())
631return c.MustBindWith(obj, b)
632}
633
634// BindJSON is a shortcut for c.MustBindWith(obj, binding.JSON).
635func (c *Context) BindJSON(obj any) error {
636return c.MustBindWith(obj, binding.JSON)
637}
638
639// BindXML is a shortcut for c.MustBindWith(obj, binding.BindXML).
640func (c *Context) BindXML(obj any) error {
641return c.MustBindWith(obj, binding.XML)
642}
643
644// BindQuery is a shortcut for c.MustBindWith(obj, binding.Query).
645func (c *Context) BindQuery(obj any) error {
646return c.MustBindWith(obj, binding.Query)
647}
648
649// BindYAML is a shortcut for c.MustBindWith(obj, binding.YAML).
650func (c *Context) BindYAML(obj any) error {
651return c.MustBindWith(obj, binding.YAML)
652}
653
654// BindTOML is a shortcut for c.MustBindWith(obj, binding.TOML).
655func (c *Context) BindTOML(obj any) error {
656return c.MustBindWith(obj, binding.TOML)
657}
658
659// BindHeader is a shortcut for c.MustBindWith(obj, binding.Header).
660func (c *Context) BindHeader(obj any) error {
661return c.MustBindWith(obj, binding.Header)
662}
663
664// BindUri binds the passed struct pointer using binding.Uri.
665// It will abort the request with HTTP 400 if any error occurs.
666func (c *Context) BindUri(obj any) error {
667if err := c.ShouldBindUri(obj); err != nil {
668c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) //nolint: errcheck
669return err
670}
671return nil
672}
673
674// MustBindWith binds the passed struct pointer using the specified binding engine.
675// It will abort the request with HTTP 400 if any error occurs.
676// See the binding package.
677func (c *Context) MustBindWith(obj any, b binding.Binding) error {
678if err := c.ShouldBindWith(obj, b); err != nil {
679c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) //nolint: errcheck
680return err
681}
682return nil
683}
684
685// ShouldBind checks the Method and Content-Type to select a binding engine automatically,
686// Depending on the "Content-Type" header different bindings are used, for example:
687//
688// "application/json" --> JSON binding
689// "application/xml" --> XML binding
690//
691// It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input.
692// It decodes the json payload into the struct specified as a pointer.
693// Like c.Bind() but this method does not set the response status code to 400 or abort if input is not valid.
694func (c *Context) ShouldBind(obj any) error {
695b := binding.Default(c.Request.Method, c.ContentType())
696return c.ShouldBindWith(obj, b)
697}
698
699// ShouldBindJSON is a shortcut for c.ShouldBindWith(obj, binding.JSON).
700func (c *Context) ShouldBindJSON(obj any) error {
701return c.ShouldBindWith(obj, binding.JSON)
702}
703
704// ShouldBindXML is a shortcut for c.ShouldBindWith(obj, binding.XML).
705func (c *Context) ShouldBindXML(obj any) error {
706return c.ShouldBindWith(obj, binding.XML)
707}
708
709// ShouldBindQuery is a shortcut for c.ShouldBindWith(obj, binding.Query).
710func (c *Context) ShouldBindQuery(obj any) error {
711return c.ShouldBindWith(obj, binding.Query)
712}
713
714// ShouldBindYAML is a shortcut for c.ShouldBindWith(obj, binding.YAML).
715func (c *Context) ShouldBindYAML(obj any) error {
716return c.ShouldBindWith(obj, binding.YAML)
717}
718
719// ShouldBindTOML is a shortcut for c.ShouldBindWith(obj, binding.TOML).
720func (c *Context) ShouldBindTOML(obj any) error {
721return c.ShouldBindWith(obj, binding.TOML)
722}
723
724// ShouldBindHeader is a shortcut for c.ShouldBindWith(obj, binding.Header).
725func (c *Context) ShouldBindHeader(obj any) error {
726return c.ShouldBindWith(obj, binding.Header)
727}
728
729// ShouldBindUri binds the passed struct pointer using the specified binding engine.
730func (c *Context) ShouldBindUri(obj any) error {
731m := make(map[string][]string)
732for _, v := range c.Params {
733m[v.Key] = []string{v.Value}
734}
735return binding.Uri.BindUri(m, obj)
736}
737
738// ShouldBindWith binds the passed struct pointer using the specified binding engine.
739// See the binding package.
740func (c *Context) ShouldBindWith(obj any, b binding.Binding) error {
741return b.Bind(c.Request, obj)
742}
743
744// ShouldBindBodyWith is similar with ShouldBindWith, but it stores the request
745// body into the context, and reuse when it is called again.
746//
747// NOTE: This method reads the body before binding. So you should use
748// ShouldBindWith for better performance if you need to call only once.
749func (c *Context) ShouldBindBodyWith(obj any, bb binding.BindingBody) (err error) {
750var body []byte
751if cb, ok := c.Get(BodyBytesKey); ok {
752if cbb, ok := cb.([]byte); ok {
753body = cbb
754}
755}
756if body == nil {
757body, err = io.ReadAll(c.Request.Body)
758if err != nil {
759return err
760}
761c.Set(BodyBytesKey, body)
762}
763return bb.BindBody(body, obj)
764}
765
766// ClientIP implements one best effort algorithm to return the real client IP.
767// It calls c.RemoteIP() under the hood, to check if the remote IP is a trusted proxy or not.
768// If it is it will then try to parse the headers defined in Engine.RemoteIPHeaders (defaulting to [X-Forwarded-For, X-Real-Ip]).
769// If the headers are not syntactically valid OR the remote IP does not correspond to a trusted proxy,
770// the remote IP (coming from Request.RemoteAddr) is returned.
771func (c *Context) ClientIP() string {
772// Check if we're running on a trusted platform, continue running backwards if error
773if c.engine.TrustedPlatform != "" {
774// Developers can define their own header of Trusted Platform or use predefined constants
775if addr := c.requestHeader(c.engine.TrustedPlatform); addr != "" {
776return addr
777}
778}
779
780// Legacy "AppEngine" flag
781if c.engine.AppEngine {
782log.Println(`The AppEngine flag is going to be deprecated. Please check issues #2723 and #2739 and use 'TrustedPlatform: gin.PlatformGoogleAppEngine' instead.`)
783if addr := c.requestHeader("X-Appengine-Remote-Addr"); addr != "" {
784return addr
785}
786}
787
788// It also checks if the remoteIP is a trusted proxy or not.
789// In order to perform this validation, it will see if the IP is contained within at least one of the CIDR blocks
790// defined by Engine.SetTrustedProxies()
791remoteIP := net.ParseIP(c.RemoteIP())
792if remoteIP == nil {
793return ""
794}
795trusted := c.engine.isTrustedProxy(remoteIP)
796
797if trusted && c.engine.ForwardedByClientIP && c.engine.RemoteIPHeaders != nil {
798for _, headerName := range c.engine.RemoteIPHeaders {
799ip, valid := c.engine.validateHeader(c.requestHeader(headerName))
800if valid {
801return ip
802}
803}
804}
805return remoteIP.String()
806}
807
808// RemoteIP parses the IP from Request.RemoteAddr, normalizes and returns the IP (without the port).
809func (c *Context) RemoteIP() string {
810ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr))
811if err != nil {
812return ""
813}
814return ip
815}
816
817// ContentType returns the Content-Type header of the request.
818func (c *Context) ContentType() string {
819return filterFlags(c.requestHeader("Content-Type"))
820}
821
822// IsWebsocket returns true if the request headers indicate that a websocket
823// handshake is being initiated by the client.
824func (c *Context) IsWebsocket() bool {
825if strings.Contains(strings.ToLower(c.requestHeader("Connection")), "upgrade") &&
826strings.EqualFold(c.requestHeader("Upgrade"), "websocket") {
827return true
828}
829return false
830}
831
832func (c *Context) requestHeader(key string) string {
833return c.Request.Header.Get(key)
834}
835
836/************************************/
837/******** RESPONSE RENDERING ********/
838/************************************/
839
840// bodyAllowedForStatus is a copy of http.bodyAllowedForStatus non-exported function.
841func bodyAllowedForStatus(status int) bool {
842switch {
843case status >= 100 && status <= 199:
844return false
845case status == http.StatusNoContent:
846return false
847case status == http.StatusNotModified:
848return false
849}
850return true
851}
852
853// Status sets the HTTP response code.
854func (c *Context) Status(code int) {
855c.Writer.WriteHeader(code)
856}
857
858// Header is an intelligent shortcut for c.Writer.Header().Set(key, value).
859// It writes a header in the response.
860// If value == "", this method removes the header `c.Writer.Header().Del(key)`
861func (c *Context) Header(key, value string) {
862if value == "" {
863c.Writer.Header().Del(key)
864return
865}
866c.Writer.Header().Set(key, value)
867}
868
869// GetHeader returns value from request headers.
870func (c *Context) GetHeader(key string) string {
871return c.requestHeader(key)
872}
873
874// GetRawData returns stream data.
875func (c *Context) GetRawData() ([]byte, error) {
876return io.ReadAll(c.Request.Body)
877}
878
879// SetSameSite with cookie
880func (c *Context) SetSameSite(samesite http.SameSite) {
881c.sameSite = samesite
882}
883
884// SetCookie adds a Set-Cookie header to the ResponseWriter's headers.
885// The provided cookie must have a valid Name. Invalid cookies may be
886// silently dropped.
887func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool) {
888if path == "" {
889path = "/"
890}
891http.SetCookie(c.Writer, &http.Cookie{
892Name: name,
893Value: url.QueryEscape(value),
894MaxAge: maxAge,
895Path: path,
896Domain: domain,
897SameSite: c.sameSite,
898Secure: secure,
899HttpOnly: httpOnly,
900})
901}
902
903// Cookie returns the named cookie provided in the request or
904// ErrNoCookie if not found. And return the named cookie is unescaped.
905// If multiple cookies match the given name, only one cookie will
906// be returned.
907func (c *Context) Cookie(name string) (string, error) {
908cookie, err := c.Request.Cookie(name)
909if err != nil {
910return "", err
911}
912val, _ := url.QueryUnescape(cookie.Value)
913return val, nil
914}
915
916// Render writes the response headers and calls render.Render to render data.
917func (c *Context) Render(code int, r render.Render) {
918c.Status(code)
919
920if !bodyAllowedForStatus(code) {
921r.WriteContentType(c.Writer)
922c.Writer.WriteHeaderNow()
923return
924}
925
926if err := r.Render(c.Writer); err != nil {
927// Pushing error to c.Errors
928_ = c.Error(err)
929c.Abort()
930}
931}
932
933// HTML renders the HTTP template specified by its file name.
934// It also updates the HTTP code and sets the Content-Type as "text/html".
935// See http://golang.org/doc/articles/wiki/
936func (c *Context) HTML(code int, name string, obj any) {
937instance := c.engine.HTMLRender.Instance(name, obj)
938c.Render(code, instance)
939}
940
941// IndentedJSON serializes the given struct as pretty JSON (indented + endlines) into the response body.
942// It also sets the Content-Type as "application/json".
943// WARNING: we recommend using this only for development purposes since printing pretty JSON is
944// more CPU and bandwidth consuming. Use Context.JSON() instead.
945func (c *Context) IndentedJSON(code int, obj any) {
946c.Render(code, render.IndentedJSON{Data: obj})
947}
948
949// SecureJSON serializes the given struct as Secure JSON into the response body.
950// Default prepends "while(1)," to response body if the given struct is array values.
951// It also sets the Content-Type as "application/json".
952func (c *Context) SecureJSON(code int, obj any) {
953c.Render(code, render.SecureJSON{Prefix: c.engine.secureJSONPrefix, Data: obj})
954}
955
956// JSONP serializes the given struct as JSON into the response body.
957// It adds padding to response body to request data from a server residing in a different domain than the client.
958// It also sets the Content-Type as "application/javascript".
959func (c *Context) JSONP(code int, obj any) {
960callback := c.DefaultQuery("callback", "")
961if callback == "" {
962c.Render(code, render.JSON{Data: obj})
963return
964}
965c.Render(code, render.JsonpJSON{Callback: callback, Data: obj})
966}
967
968// JSON serializes the given struct as JSON into the response body.
969// It also sets the Content-Type as "application/json".
970func (c *Context) JSON(code int, obj any) {
971c.Render(code, render.JSON{Data: obj})
972}
973
974// AsciiJSON serializes the given struct as JSON into the response body with unicode to ASCII string.
975// It also sets the Content-Type as "application/json".
976func (c *Context) AsciiJSON(code int, obj any) {
977c.Render(code, render.AsciiJSON{Data: obj})
978}
979
980// PureJSON serializes the given struct as JSON into the response body.
981// PureJSON, unlike JSON, does not replace special html characters with their unicode entities.
982func (c *Context) PureJSON(code int, obj any) {
983c.Render(code, render.PureJSON{Data: obj})
984}
985
986// XML serializes the given struct as XML into the response body.
987// It also sets the Content-Type as "application/xml".
988func (c *Context) XML(code int, obj any) {
989c.Render(code, render.XML{Data: obj})
990}
991
992// YAML serializes the given struct as YAML into the response body.
993func (c *Context) YAML(code int, obj any) {
994c.Render(code, render.YAML{Data: obj})
995}
996
997// TOML serializes the given struct as TOML into the response body.
998func (c *Context) TOML(code int, obj any) {
999c.Render(code, render.TOML{Data: obj})
1000}
1001
1002// ProtoBuf serializes the given struct as ProtoBuf into the response body.
1003func (c *Context) ProtoBuf(code int, obj any) {
1004c.Render(code, render.ProtoBuf{Data: obj})
1005}
1006
1007// String writes the given string into the response body.
1008func (c *Context) String(code int, format string, values ...any) {
1009c.Render(code, render.String{Format: format, Data: values})
1010}
1011
1012// Redirect returns an HTTP redirect to the specific location.
1013func (c *Context) Redirect(code int, location string) {
1014c.Render(-1, render.Redirect{
1015Code: code,
1016Location: location,
1017Request: c.Request,
1018})
1019}
1020
1021// Data writes some data into the body stream and updates the HTTP code.
1022func (c *Context) Data(code int, contentType string, data []byte) {
1023c.Render(code, render.Data{
1024ContentType: contentType,
1025Data: data,
1026})
1027}
1028
1029// DataFromReader writes the specified reader into the body stream and updates the HTTP code.
1030func (c *Context) DataFromReader(code int, contentLength int64, contentType string, reader io.Reader, extraHeaders map[string]string) {
1031c.Render(code, render.Reader{
1032Headers: extraHeaders,
1033ContentType: contentType,
1034ContentLength: contentLength,
1035Reader: reader,
1036})
1037}
1038
1039// File writes the specified file into the body stream in an efficient way.
1040func (c *Context) File(filepath string) {
1041http.ServeFile(c.Writer, c.Request, filepath)
1042}
1043
1044// FileFromFS writes the specified file from http.FileSystem into the body stream in an efficient way.
1045func (c *Context) FileFromFS(filepath string, fs http.FileSystem) {
1046defer func(old string) {
1047c.Request.URL.Path = old
1048}(c.Request.URL.Path)
1049
1050c.Request.URL.Path = filepath
1051
1052http.FileServer(fs).ServeHTTP(c.Writer, c.Request)
1053}
1054
1055var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")
1056
1057func escapeQuotes(s string) string {
1058return quoteEscaper.Replace(s)
1059}
1060
1061// FileAttachment writes the specified file into the body stream in an efficient way
1062// On the client side, the file will typically be downloaded with the given filename
1063func (c *Context) FileAttachment(filepath, filename string) {
1064if isASCII(filename) {
1065c.Writer.Header().Set("Content-Disposition", `attachment; filename="`+escapeQuotes(filename)+`"`)
1066} else {
1067c.Writer.Header().Set("Content-Disposition", `attachment; filename*=UTF-8''`+url.QueryEscape(filename))
1068}
1069http.ServeFile(c.Writer, c.Request, filepath)
1070}
1071
1072// SSEvent writes a Server-Sent Event into the body stream.
1073func (c *Context) SSEvent(name string, message any) {
1074c.Render(-1, sse.Event{
1075Event: name,
1076Data: message,
1077})
1078}
1079
1080// Stream sends a streaming response and returns a boolean
1081// indicates "Is client disconnected in middle of stream"
1082func (c *Context) Stream(step func(w io.Writer) bool) bool {
1083w := c.Writer
1084clientGone := w.CloseNotify()
1085for {
1086select {
1087case <-clientGone:
1088return true
1089default:
1090keepOpen := step(w)
1091w.Flush()
1092if !keepOpen {
1093return false
1094}
1095}
1096}
1097}
1098
1099/************************************/
1100/******** CONTENT NEGOTIATION *******/
1101/************************************/
1102
1103// Negotiate contains all negotiations data.
1104type Negotiate struct {
1105Offered []string
1106HTMLName string
1107HTMLData any
1108JSONData any
1109XMLData any
1110YAMLData any
1111Data any
1112TOMLData any
1113}
1114
1115// Negotiate calls different Render according to acceptable Accept format.
1116func (c *Context) Negotiate(code int, config Negotiate) {
1117switch c.NegotiateFormat(config.Offered...) {
1118case binding.MIMEJSON:
1119data := chooseData(config.JSONData, config.Data)
1120c.JSON(code, data)
1121
1122case binding.MIMEHTML:
1123data := chooseData(config.HTMLData, config.Data)
1124c.HTML(code, config.HTMLName, data)
1125
1126case binding.MIMEXML:
1127data := chooseData(config.XMLData, config.Data)
1128c.XML(code, data)
1129
1130case binding.MIMEYAML:
1131data := chooseData(config.YAMLData, config.Data)
1132c.YAML(code, data)
1133
1134case binding.MIMETOML:
1135data := chooseData(config.TOMLData, config.Data)
1136c.TOML(code, data)
1137
1138default:
1139c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server")) //nolint: errcheck
1140}
1141}
1142
1143// NegotiateFormat returns an acceptable Accept format.
1144func (c *Context) NegotiateFormat(offered ...string) string {
1145assert1(len(offered) > 0, "you must provide at least one offer")
1146
1147if c.Accepted == nil {
1148c.Accepted = parseAccept(c.requestHeader("Accept"))
1149}
1150if len(c.Accepted) == 0 {
1151return offered[0]
1152}
1153for _, accepted := range c.Accepted {
1154for _, offer := range offered {
1155// According to RFC 2616 and RFC 2396, non-ASCII characters are not allowed in headers,
1156// therefore we can just iterate over the string without casting it into []rune
1157i := 0
1158for ; i < len(accepted) && i < len(offer); i++ {
1159if accepted[i] == '*' || offer[i] == '*' {
1160return offer
1161}
1162if accepted[i] != offer[i] {
1163break
1164}
1165}
1166if i == len(accepted) {
1167return offer
1168}
1169}
1170}
1171return ""
1172}
1173
1174// SetAccepted sets Accept header data.
1175func (c *Context) SetAccepted(formats ...string) {
1176c.Accepted = formats
1177}
1178
1179/************************************/
1180/***** GOLANG.ORG/X/NET/CONTEXT *****/
1181/************************************/
1182
1183// hasRequestContext returns whether c.Request has Context and fallback.
1184func (c *Context) hasRequestContext() bool {
1185hasFallback := c.engine != nil && c.engine.ContextWithFallback
1186hasRequestContext := c.Request != nil && c.Request.Context() != nil
1187return hasFallback && hasRequestContext
1188}
1189
1190// Deadline returns that there is no deadline (ok==false) when c.Request has no Context.
1191func (c *Context) Deadline() (deadline time.Time, ok bool) {
1192if !c.hasRequestContext() {
1193return
1194}
1195return c.Request.Context().Deadline()
1196}
1197
1198// Done returns nil (chan which will wait forever) when c.Request has no Context.
1199func (c *Context) Done() <-chan struct{} {
1200if !c.hasRequestContext() {
1201return nil
1202}
1203return c.Request.Context().Done()
1204}
1205
1206// Err returns nil when c.Request has no Context.
1207func (c *Context) Err() error {
1208if !c.hasRequestContext() {
1209return nil
1210}
1211return c.Request.Context().Err()
1212}
1213
1214// Value returns the value associated with this context for key, or nil
1215// if no value is associated with key. Successive calls to Value with
1216// the same key returns the same result.
1217func (c *Context) Value(key any) any {
1218if key == 0 {
1219return c.Request
1220}
1221if key == ContextKey {
1222return c
1223}
1224if keyAsString, ok := key.(string); ok {
1225if val, exists := c.Get(keyAsString); exists {
1226return val
1227}
1228}
1229if !c.hasRequestContext() {
1230return nil
1231}
1232return c.Request.Context().Value(key)
1233}
1234