gin-gonic / gin
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

5
package gin
6

7
import (
8
	"errors"
9
	"fmt"
10
	"io"
11
	"io/ioutil"
12
	"math"
13
	"mime/multipart"
14
	"net"
15
	"net/http"
16
	"net/url"
17
	"os"
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.
28
const (
29
	MIMEJSON              = binding.MIMEJSON
30
	MIMEHTML              = binding.MIMEHTML
31
	MIMEXML               = binding.MIMEXML
32
	MIMEXML2              = binding.MIMEXML2
33
	MIMEPlain             = binding.MIMEPlain
34
	MIMEPOSTForm          = binding.MIMEPOSTForm
35
	MIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm
36
	MIMEYAML              = binding.MIMEYAML
37
)
38

39
// BodyBytesKey indicates a default body bytes key.
40
const BodyBytesKey = "_gin-gonic/gin/bodybyteskey"
41

42
const abortIndex int8 = math.MaxInt8 / 2
43

44
// Context is the most important part of gin. It allows us to pass variables between middleware,
45
// manage the flow, validate the JSON of a request and render a JSON response for example.
46
type Context struct {
47
	writermem responseWriter
48
	Request   *http.Request
49
	Writer    ResponseWriter
50

51
	Params   Params
52
	handlers HandlersChain
53
	index    int8
54
	fullPath string
55

56
	engine *Engine
57
	params *Params
58

59
	// This mutex protect Keys map
60
	mu sync.RWMutex
61

62
	// Keys is a key/value pair exclusively for the context of each request.
63
	Keys map[string]interface{}
64

65
	// Errors is a list of errors attached to all the handlers/middlewares who used this context.
66
	Errors errorMsgs
67

68
	// Accepted defines a list of manually accepted formats for content negotiation.
69
	Accepted []string
70

71
	// queryCache use url.ParseQuery cached the param query result from c.Request.URL.Query()
72
	queryCache url.Values
73

74
	// formCache use url.ParseQuery cached PostForm contains the parsed form data from POST, PATCH,
75
	// or PUT body parameters.
76
	formCache url.Values
77

78
	// SameSite allows a server to define a cookie attribute making it impossible for
79
	// the browser to send this cookie along with cross-site requests.
80
	sameSite http.SameSite
81
}
82

83
/************************************/
84
/********** CONTEXT CREATION ********/
85
/************************************/
86

87
func (c *Context) reset() {
88 151
	c.Writer = &c.writermem
89 151
	c.Params = c.Params[0:0]
90 151
	c.handlers = nil
91 151
	c.index = -1
92

93 151
	c.fullPath = ""
94 151
	c.Keys = nil
95 151
	c.Errors = c.Errors[0:0]
96 151
	c.Accepted = nil
97 151
	c.queryCache = nil
98 151
	c.formCache = nil
99 151
	*c.params = (*c.params)[0:0]
100
}
101

102
// Copy returns a copy of the current context that can be safely used outside the request's scope.
103
// This has to be used when the context has to be passed to a goroutine.
104
func (c *Context) Copy() *Context {
105
	cp := Context{
106 151
		writermem: c.writermem,
107 151
		Request:   c.Request,
108 151
		Params:    c.Params,
109 151
		engine:    c.engine,
110
	}
111 151
	cp.writermem.ResponseWriter = nil
112 151
	cp.Writer = &cp.writermem
113 151
	cp.index = abortIndex
114 151
	cp.handlers = nil
115 151
	cp.Keys = map[string]interface{}{}
116
	for k, v := range c.Keys {
117 151
		cp.Keys[k] = v
118
	}
119 151
	paramCopy := make([]Param, len(cp.Params))
120 151
	copy(paramCopy, cp.Params)
121 151
	cp.Params = paramCopy
122 151
	return &cp
123
}
124

125
// HandlerName returns the main handler's name. For example if the handler is "handleGetUsers()",
126
// this function will return "main.handleGetUsers".
127
func (c *Context) HandlerName() string {
128 151
	return nameOfFunction(c.handlers.Last())
129
}
130

131
// HandlerNames returns a list of all registered handlers for this context in descending order,
132
// following the semantics of HandlerName()
133
func (c *Context) HandlerNames() []string {
134 151
	hn := make([]string, 0, len(c.handlers))
135
	for _, val := range c.handlers {
136 151
		hn = append(hn, nameOfFunction(val))
137
	}
138 151
	return hn
139
}
140

141
// Handler returns the main handler.
142
func (c *Context) Handler() HandlerFunc {
143 151
	return c.handlers.Last()
144
}
145

146
// FullPath returns a matched route full path. For not found routes
147
// returns an empty string.
148
//     router.GET("/user/:id", func(c *gin.Context) {
149
//         c.FullPath() == "/user/:id" // true
150
//     })
151
func (c *Context) FullPath() string {
152 151
	return c.fullPath
153
}
154

155
/************************************/
156
/*********** FLOW CONTROL ***********/
157
/************************************/
158

159
// Next should be used only inside middleware.
160
// It executes the pending handlers in the chain inside the calling handler.
161
// See example in GitHub.
162
func (c *Context) Next() {
163 151
	c.index++
164
	for c.index < int8(len(c.handlers)) {
165 151
		c.handlers[c.index](c)
166 151
		c.index++
167
	}
168
}
169

170
// IsAborted returns true if the current context was aborted.
171
func (c *Context) IsAborted() bool {
172 151
	return c.index >= abortIndex
173
}
174

175
// Abort prevents pending handlers from being called. Note that this will not stop the current handler.
176
// Let's say you have an authorization middleware that validates that the current request is authorized.
177
// If the authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers
178
// for this request are not called.
179
func (c *Context) Abort() {
180 151
	c.index = abortIndex
181
}
182

183
// AbortWithStatus calls `Abort()` and writes the headers with the specified status code.
184
// For example, a failed attempt to authenticate a request could use: context.AbortWithStatus(401).
185
func (c *Context) AbortWithStatus(code int) {
186 151
	c.Status(code)
187 151
	c.Writer.WriteHeaderNow()
188 151
	c.Abort()
189
}
190

191
// AbortWithStatusJSON calls `Abort()` and then `JSON` internally.
192
// This method stops the chain, writes the status code and return a JSON body.
193
// It also sets the Content-Type as "application/json".
194
func (c *Context) AbortWithStatusJSON(code int, jsonObj interface{}) {
195 151
	c.Abort()
196 151
	c.JSON(code, jsonObj)
197
}
198

199
// AbortWithError calls `AbortWithStatus()` and `Error()` internally.
200
// This method stops the chain, writes the status code and pushes the specified error to `c.Errors`.
201
// See Context.Error() for more details.
202
func (c *Context) AbortWithError(code int, err error) *Error {
203 151
	c.AbortWithStatus(code)
204 151
	return c.Error(err)
205
}
206

207
/************************************/
208
/********* ERROR MANAGEMENT *********/
209
/************************************/
210

211
// Error attaches an error to the current context. The error is pushed to a list of errors.
212
// It's a good idea to call Error for each error that occurred during the resolution of a request.
213
// A middleware can be used to collect all the errors and push them to a database together,
214
// print a log, or append it in the HTTP response.
215
// Error will panic if err is nil.
216
func (c *Context) Error(err error) *Error {
217 151
	if err == nil {
218 151
		panic("err is nil")
219
	}
220

221 151
	parsedError, ok := err.(*Error)
222 151
	if !ok {
223 151
		parsedError = &Error{
224 151
			Err:  err,
225 151
			Type: ErrorTypePrivate,
226
		}
227
	}
228

229 151
	c.Errors = append(c.Errors, parsedError)
230 151
	return parsedError
231
}
232

233
/************************************/
234
/******** METADATA MANAGEMENT********/
235
/************************************/
236

237
// Set is used to store a new key/value pair exclusively for this context.
238
// It also lazy initializes  c.Keys if it was not used previously.
239
func (c *Context) Set(key string, value interface{}) {
240 151
	c.mu.Lock()
241 151
	if c.Keys == nil {
242 151
		c.Keys = make(map[string]interface{})
243
	}
244

245 151
	c.Keys[key] = value
246 151
	c.mu.Unlock()
247
}
248

249
// Get returns the value for the given key, ie: (value, true).
250
// If the value does not exists it returns (nil, false)
251
func (c *Context) Get(key string) (value interface{}, exists bool) {
252 151
	c.mu.RLock()
253 151
	value, exists = c.Keys[key]
254 151
	c.mu.RUnlock()
255 151
	return
256
}
257

258
// MustGet returns the value for the given key if it exists, otherwise it panics.
259
func (c *Context) MustGet(key string) interface{} {
260 151
	if value, exists := c.Get(key); exists {
261 151
		return value
262
	}
263 151
	panic("Key \"" + key + "\" does not exist")
264
}
265

266
// GetString returns the value associated with the key as a string.
267
func (c *Context) GetString(key string) (s string) {
268 151
	if val, ok := c.Get(key); ok && val != nil {
269 151
		s, _ = val.(string)
270
	}
271 151
	return
272
}
273

274
// GetBool returns the value associated with the key as a boolean.
275
func (c *Context) GetBool(key string) (b bool) {
276 151
	if val, ok := c.Get(key); ok && val != nil {
277 151
		b, _ = val.(bool)
278
	}
279 151
	return
280
}
281

282
// GetInt returns the value associated with the key as an integer.
283
func (c *Context) GetInt(key string) (i int) {
284 151
	if val, ok := c.Get(key); ok && val != nil {
285 151
		i, _ = val.(int)
286
	}
287 151
	return
288
}
289

290
// GetInt64 returns the value associated with the key as an integer.
291
func (c *Context) GetInt64(key string) (i64 int64) {
292 151
	if val, ok := c.Get(key); ok && val != nil {
293 151
		i64, _ = val.(int64)
294
	}
295 151
	return
296
}
297

298
// GetUint returns the value associated with the key as an unsigned integer.
299
func (c *Context) GetUint(key string) (ui uint) {
300 151
	if val, ok := c.Get(key); ok && val != nil {
301 151
		ui, _ = val.(uint)
302
	}
303 151
	return
304
}
305

306
// GetUint64 returns the value associated with the key as an unsigned integer.
307
func (c *Context) GetUint64(key string) (ui64 uint64) {
308 151
	if val, ok := c.Get(key); ok && val != nil {
309 151
		ui64, _ = val.(uint64)
310
	}
311 151
	return
312
}
313

314
// GetFloat64 returns the value associated with the key as a float64.
315
func (c *Context) GetFloat64(key string) (f64 float64) {
316 151
	if val, ok := c.Get(key); ok && val != nil {
317 151
		f64, _ = val.(float64)
318
	}
319 151
	return
320
}
321

322
// GetTime returns the value associated with the key as time.
323
func (c *Context) GetTime(key string) (t time.Time) {
324 151
	if val, ok := c.Get(key); ok && val != nil {
325 151
		t, _ = val.(time.Time)
326
	}
327 151
	return
328
}
329

330
// GetDuration returns the value associated with the key as a duration.
331
func (c *Context) GetDuration(key string) (d time.Duration) {
332 151
	if val, ok := c.Get(key); ok && val != nil {
333 151
		d, _ = val.(time.Duration)
334
	}
335 151
	return
336
}
337

338
// GetStringSlice returns the value associated with the key as a slice of strings.
339
func (c *Context) GetStringSlice(key string) (ss []string) {
340 151
	if val, ok := c.Get(key); ok && val != nil {
341 151
		ss, _ = val.([]string)
342
	}
343 151
	return
344
}
345

346
// GetStringMap returns the value associated with the key as a map of interfaces.
347
func (c *Context) GetStringMap(key string) (sm map[string]interface{}) {
348 151
	if val, ok := c.Get(key); ok && val != nil {
349 151
		sm, _ = val.(map[string]interface{})
350
	}
351 151
	return
352
}
353

354
// GetStringMapString returns the value associated with the key as a map of strings.
355
func (c *Context) GetStringMapString(key string) (sms map[string]string) {
356 151
	if val, ok := c.Get(key); ok && val != nil {
357 151
		sms, _ = val.(map[string]string)
358
	}
359 151
	return
360
}
361

362
// GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.
363
func (c *Context) GetStringMapStringSlice(key string) (smss map[string][]string) {
364 151
	if val, ok := c.Get(key); ok && val != nil {
365 151
		smss, _ = val.(map[string][]string)
366
	}
367 151
	return
368
}
369

370
/************************************/
371
/************ INPUT DATA ************/
372
/************************************/
373

374
// Param returns the value of the URL param.
375
// It is a shortcut for c.Params.ByName(key)
376
//     router.GET("/user/:id", func(c *gin.Context) {
377
//         // a GET request to /user/john
378
//         id := c.Param("id") // id == "john"
379
//     })
380
func (c *Context) Param(key string) string {
381 151
	return c.Params.ByName(key)
382
}
383

384
// Query returns the keyed url query value if it exists,
385
// otherwise it returns an empty string `("")`.
386
// It is shortcut for `c.Request.URL.Query().Get(key)`
387
//     GET /path?id=1234&name=Manu&value=
388
// 	   c.Query("id") == "1234"
389
// 	   c.Query("name") == "Manu"
390
// 	   c.Query("value") == ""
391
// 	   c.Query("wtf") == ""
392
func (c *Context) Query(key string) string {
393 151
	value, _ := c.GetQuery(key)
394 151
	return value
395
}
396

397
// DefaultQuery returns the keyed url query value if it exists,
398
// otherwise it returns the specified defaultValue string.
399
// See: Query() and GetQuery() for further information.
400
//     GET /?name=Manu&lastname=
401
//     c.DefaultQuery("name", "unknown") == "Manu"
402
//     c.DefaultQuery("id", "none") == "none"
403
//     c.DefaultQuery("lastname", "none") == ""
404
func (c *Context) DefaultQuery(key, defaultValue string) string {
405 151
	if value, ok := c.GetQuery(key); ok {
406 151
		return value
407
	}
408 151
	return defaultValue
409
}
410

411
// GetQuery is like Query(), it returns the keyed url query value
412
// if it exists `(value, true)` (even when the value is an empty string),
413
// otherwise it returns `("", false)`.
414
// It is shortcut for `c.Request.URL.Query().Get(key)`
415
//     GET /?name=Manu&lastname=
416
//     ("Manu", true) == c.GetQuery("name")
417
//     ("", false) == c.GetQuery("id")
418
//     ("", true) == c.GetQuery("lastname")
419
func (c *Context) GetQuery(key string) (string, bool) {
420 151
	if values, ok := c.GetQueryArray(key); ok {
421 151
		return values[0], ok
422
	}
423 151
	return "", false
424
}
425

426
// QueryArray returns a slice of strings for a given query key.
427
// The length of the slice depends on the number of params with the given key.
428
func (c *Context) QueryArray(key string) []string {
429 151
	values, _ := c.GetQueryArray(key)
430 151
	return values
431
}
432

433
func (c *Context) initQueryCache() {
434 151
	if c.queryCache == nil {
435 151
		if c.Request != nil {
436 151
			c.queryCache = c.Request.URL.Query()
437 151
		} else {
438 151
			c.queryCache = url.Values{}
439
		}
440
	}
441
}
442

443
// GetQueryArray returns a slice of strings for a given query key, plus
444
// a boolean value whether at least one value exists for the given key.
445
func (c *Context) GetQueryArray(key string) ([]string, bool) {
446 151
	c.initQueryCache()
447 151
	if values, ok := c.queryCache[key]; ok && len(values) > 0 {
448 151
		return values, true
449
	}
450 151
	return []string{}, false
451
}
452

453
// QueryMap returns a map for a given query key.
454
func (c *Context) QueryMap(key string) map[string]string {
455 151
	dicts, _ := c.GetQueryMap(key)
456 151
	return dicts
457
}
458

459
// GetQueryMap returns a map for a given query key, plus a boolean value
460
// whether at least one value exists for the given key.
461
func (c *Context) GetQueryMap(key string) (map[string]string, bool) {
462 151
	c.initQueryCache()
463 151
	return c.get(c.queryCache, key)
464
}
465

466
// PostForm returns the specified key from a POST urlencoded form or multipart form
467
// when it exists, otherwise it returns an empty string `("")`.
468
func (c *Context) PostForm(key string) string {
469 151
	value, _ := c.GetPostForm(key)
470 151
	return value
471
}
472

473
// DefaultPostForm returns the specified key from a POST urlencoded form or multipart form
474
// when it exists, otherwise it returns the specified defaultValue string.
475
// See: PostForm() and GetPostForm() for further information.
476
func (c *Context) DefaultPostForm(key, defaultValue string) string {
477 151
	if value, ok := c.GetPostForm(key); ok {
478 151
		return value
479
	}
480 151
	return defaultValue
481
}
482

483
// GetPostForm is like PostForm(key). It returns the specified key from a POST urlencoded
484
// form or multipart form when it exists `(value, true)` (even when the value is an empty string),
485
// otherwise it returns ("", false).
486
// For example, during a PATCH request to update the user's email:
487
//     email=mail@example.com  -->  ("mail@example.com", true) := GetPostForm("email") // set email to "mail@example.com"
488
// 	   email=                  -->  ("", true) := GetPostForm("email") // set email to ""
489
//                             -->  ("", false) := GetPostForm("email") // do nothing with email
490
func (c *Context) GetPostForm(key string) (string, bool) {
491 151
	if values, ok := c.GetPostFormArray(key); ok {
492 151
		return values[0], ok
493
	}
494 151
	return "", false
495
}
496

497
// PostFormArray returns a slice of strings for a given form key.
498
// The length of the slice depends on the number of params with the given key.
499
func (c *Context) PostFormArray(key string) []string {
500 151
	values, _ := c.GetPostFormArray(key)
501 151
	return values
502
}
503

504
func (c *Context) initFormCache() {
505 151
	if c.formCache == nil {
506 151
		c.formCache = make(url.Values)
507 151
		req := c.Request
508 151
		if err := req.ParseMultipartForm(c.engine.MaxMultipartMemory); err != nil {
509 151
			if err != http.ErrNotMultipart {
510 0
				debugPrint("error on parse multipart form array: %v", err)
511
			}
512
		}
513 151
		c.formCache = req.PostForm
514
	}
515
}
516

517
// GetPostFormArray returns a slice of strings for a given form key, plus
518
// a boolean value whether at least one value exists for the given key.
519
func (c *Context) GetPostFormArray(key string) ([]string, bool) {
520 151
	c.initFormCache()
521 151
	if values := c.formCache[key]; len(values) > 0 {
522 151
		return values, true
523
	}
524 151
	return []string{}, false
525
}
526

527
// PostFormMap returns a map for a given form key.
528
func (c *Context) PostFormMap(key string) map[string]string {
529 151
	dicts, _ := c.GetPostFormMap(key)
530 151
	return dicts
531
}
532

533
// GetPostFormMap returns a map for a given form key, plus a boolean value
534
// whether at least one value exists for the given key.
535
func (c *Context) GetPostFormMap(key string) (map[string]string, bool) {
536 151
	c.initFormCache()
537 151
	return c.get(c.formCache, key)
538
}
539

540
// get is an internal method and returns a map which satisfy conditions.
541
func (c *Context) get(m map[string][]string, key string) (map[string]string, bool) {
542 151
	dicts := make(map[string]string)
543 151
	exist := false
544
	for k, v := range m {
545 151
		if i := strings.IndexByte(k, '['); i >= 1 && k[0:i] == key {
546 151
			if j := strings.IndexByte(k[i+1:], ']'); j >= 1 {
547 151
				exist = true
548 151
				dicts[k[i+1:][:j]] = v[0]
549
			}
550
		}
551
	}
552 151
	return dicts, exist
553
}
554

555
// FormFile returns the first file for the provided form key.
556
func (c *Context) FormFile(name string) (*multipart.FileHeader, error) {
557 151
	if c.Request.MultipartForm == nil {
558 151
		if err := c.Request.ParseMultipartForm(c.engine.MaxMultipartMemory); err != nil {
559 151
			return nil, err
560
		}
561
	}
562 151
	f, fh, err := c.Request.FormFile(name)
563 151
	if err != nil {
564 0
		return nil, err
565
	}
566 151
	f.Close()
567 151
	return fh, err
568
}
569

570
// MultipartForm is the parsed multipart form, including file uploads.
571
func (c *Context) MultipartForm() (*multipart.Form, error) {
572 151
	err := c.Request.ParseMultipartForm(c.engine.MaxMultipartMemory)
573 151
	return c.Request.MultipartForm, err
574
}
575

576
// SaveUploadedFile uploads the form file to specific dst.
577
func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error {
578 151
	src, err := file.Open()
579 151
	if err != nil {
580 151
		return err
581
	}
582 151
	defer src.Close()
583

584 151
	out, err := os.Create(dst)
585 151
	if err != nil {
586 151
		return err
587
	}
588 151
	defer out.Close()
589

590 151
	_, err = io.Copy(out, src)
591 151
	return err
592
}
593

594
// Bind checks the Content-Type to select a binding engine automatically,
595
// Depending the "Content-Type" header different bindings are used:
596
//     "application/json" --> JSON binding
597
//     "application/xml"  --> XML binding
598
// otherwise --> returns an error.
599
// It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input.
600
// It decodes the json payload into the struct specified as a pointer.
601
// It writes a 400 error and sets Content-Type header "text/plain" in the response if input is not valid.
602
func (c *Context) Bind(obj interface{}) error {
603 151
	b := binding.Default(c.Request.Method, c.ContentType())
604 151
	return c.MustBindWith(obj, b)
605
}
606

607
// BindJSON is a shortcut for c.MustBindWith(obj, binding.JSON).
608
func (c *Context) BindJSON(obj interface{}) error {
609 151
	return c.MustBindWith(obj, binding.JSON)
610
}
611

612
// BindXML is a shortcut for c.MustBindWith(obj, binding.BindXML).
613
func (c *Context) BindXML(obj interface{}) error {
614 151
	return c.MustBindWith(obj, binding.XML)
615
}
616

617
// BindQuery is a shortcut for c.MustBindWith(obj, binding.Query).
618
func (c *Context) BindQuery(obj interface{}) error {
619 151
	return c.MustBindWith(obj, binding.Query)
620
}
621

622
// BindYAML is a shortcut for c.MustBindWith(obj, binding.YAML).
623
func (c *Context) BindYAML(obj interface{}) error {
624 151
	return c.MustBindWith(obj, binding.YAML)
625
}
626

627
// BindHeader is a shortcut for c.MustBindWith(obj, binding.Header).
628
func (c *Context) BindHeader(obj interface{}) error {
629 151
	return c.MustBindWith(obj, binding.Header)
630
}
631

632
// BindUri binds the passed struct pointer using binding.Uri.
633
// It will abort the request with HTTP 400 if any error occurs.
634
func (c *Context) BindUri(obj interface{}) error {
635 151
	if err := c.ShouldBindUri(obj); err != nil {
636 151
		c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) // nolint: errcheck
637 151
		return err
638
	}
639 151
	return nil
640
}
641

642
// MustBindWith binds the passed struct pointer using the specified binding engine.
643
// It will abort the request with HTTP 400 if any error occurs.
644
// See the binding package.
645
func (c *Context) MustBindWith(obj interface{}, b binding.Binding) error {
646 151
	if err := c.ShouldBindWith(obj, b); err != nil {
647 151
		c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) // nolint: errcheck
648 151
		return err
649
	}
650 151
	return nil
651
}
652

653
// ShouldBind checks the Content-Type to select a binding engine automatically,
654
// Depending the "Content-Type" header different bindings are used:
655
//     "application/json" --> JSON binding
656
//     "application/xml"  --> XML binding
657
// otherwise --> returns an error
658
// It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input.
659
// It decodes the json payload into the struct specified as a pointer.
660
// Like c.Bind() but this method does not set the response status code to 400 and abort if the json is not valid.
661
func (c *Context) ShouldBind(obj interface{}) error {
662 151
	b := binding.Default(c.Request.Method, c.ContentType())
663 151
	return c.ShouldBindWith(obj, b)
664
}
665

666
// ShouldBindJSON is a shortcut for c.ShouldBindWith(obj, binding.JSON).
667
func (c *Context) ShouldBindJSON(obj interface{}) error {
668 151
	return c.ShouldBindWith(obj, binding.JSON)
669
}
670

671
// ShouldBindXML is a shortcut for c.ShouldBindWith(obj, binding.XML).
672
func (c *Context) ShouldBindXML(obj interface{}) error {
673 151
	return c.ShouldBindWith(obj, binding.XML)
674
}
675

676
// ShouldBindQuery is a shortcut for c.ShouldBindWith(obj, binding.Query).
677
func (c *Context) ShouldBindQuery(obj interface{}) error {
678 151
	return c.ShouldBindWith(obj, binding.Query)
679
}
680

681
// ShouldBindYAML is a shortcut for c.ShouldBindWith(obj, binding.YAML).
682
func (c *Context) ShouldBindYAML(obj interface{}) error {
683 151
	return c.ShouldBindWith(obj, binding.YAML)
684
}
685

686
// ShouldBindHeader is a shortcut for c.ShouldBindWith(obj, binding.Header).
687
func (c *Context) ShouldBindHeader(obj interface{}) error {
688 151
	return c.ShouldBindWith(obj, binding.Header)
689
}
690

691
// ShouldBindUri binds the passed struct pointer using the specified binding engine.
692
func (c *Context) ShouldBindUri(obj interface{}) error {
693 151
	m := make(map[string][]string)
694
	for _, v := range c.Params {
695 151
		m[v.Key] = []string{v.Value}
696
	}
697 151
	return binding.Uri.BindUri(m, obj)
698
}
699

700
// ShouldBindWith binds the passed struct pointer using the specified binding engine.
701
// See the binding package.
702
func (c *Context) ShouldBindWith(obj interface{}, b binding.Binding) error {
703 151
	return b.Bind(c.Request, obj)
704
}
705

706
// ShouldBindBodyWith is similar with ShouldBindWith, but it stores the request
707
// body into the context, and reuse when it is called again.
708
//
709
// NOTE: This method reads the body before binding. So you should use
710
// ShouldBindWith for better performance if you need to call only once.
711
func (c *Context) ShouldBindBodyWith(obj interface{}, bb binding.BindingBody) (err error) {
712 151
	var body []byte
713 151
	if cb, ok := c.Get(BodyBytesKey); ok {
714 151
		if cbb, ok := cb.([]byte); ok {
715 151
			body = cbb
716
		}
717
	}
718 151
	if body == nil {
719 151
		body, err = ioutil.ReadAll(c.Request.Body)
720 151
		if err != nil {
721 0
			return err
722
		}
723 151
		c.Set(BodyBytesKey, body)
724
	}
725 151
	return bb.BindBody(body, obj)
726
}
727

728
// ClientIP implements a best effort algorithm to return the real client IP, it parses
729
// X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy.
730
// Use X-Forwarded-For before X-Real-Ip as nginx uses X-Real-Ip with the proxy's IP.
731
func (c *Context) ClientIP() string {
732 151
	if c.engine.ForwardedByClientIP {
733 151
		clientIP := c.requestHeader("X-Forwarded-For")
734 151
		clientIP = strings.TrimSpace(strings.Split(clientIP, ",")[0])
735 151
		if clientIP == "" {
736 151
			clientIP = strings.TrimSpace(c.requestHeader("X-Real-Ip"))
737
		}
738 151
		if clientIP != "" {
739 151
			return clientIP
740
		}
741
	}
742

743 151
	if c.engine.AppEngine {
744 151
		if addr := c.requestHeader("X-Appengine-Remote-Addr"); addr != "" {
745 151
			return addr
746
		}
747
	}
748

749 151
	if ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr)); err == nil {
750 151
		return ip
751
	}
752

753 151
	return ""
754
}
755

756
// ContentType returns the Content-Type header of the request.
757
func (c *Context) ContentType() string {
758 151
	return filterFlags(c.requestHeader("Content-Type"))
759
}
760

761
// IsWebsocket returns true if the request headers indicate that a websocket
762
// handshake is being initiated by the client.
763
func (c *Context) IsWebsocket() bool {
764 151
	if strings.Contains(strings.ToLower(c.requestHeader("Connection")), "upgrade") &&
765 151
		strings.EqualFold(c.requestHeader("Upgrade"), "websocket") {
766 151
		return true
767
	}
768 151
	return false
769
}
770

771
func (c *Context) requestHeader(key string) string {
772 151
	return c.Request.Header.Get(key)
773
}
774

775
/************************************/
776
/******** RESPONSE RENDERING ********/
777
/************************************/
778

779
// bodyAllowedForStatus is a copy of http.bodyAllowedForStatus non-exported function.
780
func bodyAllowedForStatus(status int) bool {
781 151
	switch {
782 151
	case status >= 100 && status <= 199:
783 151
		return false
784 151
	case status == http.StatusNoContent:
785 151
		return false
786 151
	case status == http.StatusNotModified:
787 151
		return false
788
	}
789 151
	return true
790
}
791

792
// Status sets the HTTP response code.
793
func (c *Context) Status(code int) {
794 151
	c.Writer.WriteHeader(code)
795
}
796

797
// Header is a intelligent shortcut for c.Writer.Header().Set(key, value).
798
// It writes a header in the response.
799
// If value == "", this method removes the header `c.Writer.Header().Del(key)`
800
func (c *Context) Header(key, value string) {
801 151
	if value == "" {
802 151
		c.Writer.Header().Del(key)
803 151
		return
804
	}
805 151
	c.Writer.Header().Set(key, value)
806
}
807

808
// GetHeader returns value from request headers.
809
func (c *Context) GetHeader(key string) string {
810 151
	return c.requestHeader(key)
811
}
812

813
// GetRawData return stream data.
814
func (c *Context) GetRawData() ([]byte, error) {
815 151
	return ioutil.ReadAll(c.Request.Body)
816
}
817

818
// SetSameSite with cookie
819
func (c *Context) SetSameSite(samesite http.SameSite) {
820 151
	c.sameSite = samesite
821
}
822

823
// SetCookie adds a Set-Cookie header to the ResponseWriter's headers.
824
// The provided cookie must have a valid Name. Invalid cookies may be
825
// silently dropped.
826
func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool) {
827 151
	if path == "" {
828 151
		path = "/"
829
	}
830 151
	http.SetCookie(c.Writer, &http.Cookie{
831 151
		Name:     name,
832 151
		Value:    url.QueryEscape(value),
833 151
		MaxAge:   maxAge,
834 151
		Path:     path,
835 151
		Domain:   domain,
836 151
		SameSite: c.sameSite,
837 151
		Secure:   secure,
838