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 14
	c.Writer = &c.writermem
89 14
	c.Params = c.Params[0:0]
90 14
	c.handlers = nil
91 14
	c.index = -1
92

93 14
	c.fullPath = ""
94 14
	c.Keys = nil
95 14
	c.Errors = c.Errors[0:0]
96 14
	c.Accepted = nil
97 14
	c.queryCache = nil
98 14
	c.formCache = nil
99 14
	*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 14
		writermem: c.writermem,
107 14
		Request:   c.Request,
108 14
		Params:    c.Params,
109 14
		engine:    c.engine,
110
	}
111 14
	cp.writermem.ResponseWriter = nil
112 14
	cp.Writer = &cp.writermem
113 14
	cp.index = abortIndex
114 14
	cp.handlers = nil
115 14
	cp.Keys = map[string]interface{}{}
116
	for k, v := range c.Keys {
117 14
		cp.Keys[k] = v
118
	}
119 14
	paramCopy := make([]Param, len(cp.Params))
120 14
	copy(paramCopy, cp.Params)
121 14
	cp.Params = paramCopy
122 14
	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 14
	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 14
	hn := make([]string, 0, len(c.handlers))
135
	for _, val := range c.handlers {
136 14
		hn = append(hn, nameOfFunction(val))
137
	}
138 14
	return hn
139
}
140

141
// Handler returns the main handler.
142
func (c *Context) Handler() HandlerFunc {
143 14
	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 14
	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 14
	c.index++
164
	for c.index < int8(len(c.handlers)) {
165 14
		c.handlers[c.index](c)
166 14
		c.index++
167
	}
168
}
169

170
// IsAborted returns true if the current context was aborted.
171
func (c *Context) IsAborted() bool {
172 14
	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 14
	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 14
	c.Status(code)
187 14
	c.Writer.WriteHeaderNow()
188 14
	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 14
	c.Abort()
196 14
	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 14
	c.AbortWithStatus(code)
204 14
	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 14
	if err == nil {
218 14
		panic("err is nil")
219
	}
220

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

229 14
	c.Errors = append(c.Errors, parsedError)
230 14
	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 14
	c.mu.Lock()
241 14
	if c.Keys == nil {
242 14
		c.Keys = make(map[string]interface{})
243
	}
244

245 14
	c.Keys[key] = value
246 14
	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 14
	c.mu.RLock()
253 14
	value, exists = c.Keys[key]
254 14
	c.mu.RUnlock()
255 14
	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 14
	if value, exists := c.Get(key); exists {
261 14
		return value
262
	}
263 14
	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 14
	if val, ok := c.Get(key); ok && val != nil {
269 14
		s, _ = val.(string)
270
	}
271 14
	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 14
	if val, ok := c.Get(key); ok && val != nil {
277 14
		b, _ = val.(bool)
278
	}
279 14
	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 14
	if val, ok := c.Get(key); ok && val != nil {
285 14
		i, _ = val.(int)
286
	}
287 14
	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 14
	if val, ok := c.Get(key); ok && val != nil {
293 14
		i64, _ = val.(int64)
294
	}
295 14
	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 14
	if val, ok := c.Get(key); ok && val != nil {
301 14
		ui, _ = val.(uint)
302
	}
303 14
	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 14
	if val, ok := c.Get(key); ok && val != nil {
309 14
		ui64, _ = val.(uint64)
310
	}
311 14
	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 14
	if val, ok := c.Get(key); ok && val != nil {
317 14
		f64, _ = val.(float64)
318
	}
319 14
	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 14
	if val, ok := c.Get(key); ok && val != nil {
325 14
		t, _ = val.(time.Time)
326
	}
327 14
	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 14
	if val, ok := c.Get(key); ok && val != nil {
333 14
		d, _ = val.(time.Duration)
334
	}
335 14
	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 14
	if val, ok := c.Get(key); ok && val != nil {
341 14
		ss, _ = val.([]string)
342
	}
343 14
	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 14
	if val, ok := c.Get(key); ok && val != nil {
349 14
		sm, _ = val.(map[string]interface{})
350
	}
351 14
	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 14
	if val, ok := c.Get(key); ok && val != nil {
357 14
		sms, _ = val.(map[string]string)
358
	}
359 14
	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 14
	if val, ok := c.Get(key); ok && val != nil {
365 14
		smss, _ = val.(map[string][]string)
366
	}
367 14
	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 14
	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 14
	value, _ := c.GetQuery(key)
394 14
	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 14
	if value, ok := c.GetQuery(key); ok {
406 14
		return value
407
	}
408 14
	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 14
	if values, ok := c.GetQueryArray(key); ok {
421 14
		return values[0], ok
422
	}
423 14
	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 14
	values, _ := c.GetQueryArray(key)
430 14
	return values
431
}
432

433
func (c *Context) initQueryCache() {
434 14
	if c.queryCache == nil {
435 14
		if c.Request != nil {
436 14
			c.queryCache = c.Request.URL.Query()
437 14
		} else {
438 14
			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 14
	c.initQueryCache()
447 14
	if values, ok := c.queryCache[key]; ok && len(values) > 0 {
448 14
		return values, true
449
	}
450 14
	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 14
	dicts, _ := c.GetQueryMap(key)
456 14
	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 14
	c.initQueryCache()
463 14
	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 14
	value, _ := c.GetPostForm(key)
470 14
	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 14
	if value, ok := c.GetPostForm(key); ok {
478 14
		return value
479
	}
480 14
	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 14
	if values, ok := c.GetPostFormArray(key); ok {
492 14
		return values[0], ok
493
	}
494 14
	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 14
	values, _ := c.GetPostFormArray(key)
501 14
	return values
502
}
503

504
func (c *Context) initFormCache() {
505 14
	if c.formCache == nil {
506 14
		c.formCache = make(url.Values)
507 14
		req := c.Request
508 14
		if err := req.ParseMultipartForm(c.engine.MaxMultipartMemory); err != nil {
509 14
			if err != http.ErrNotMultipart {
510 0
				debugPrint("error on parse multipart form array: %v", err)
511
			}
512
		}
513 14
		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 14
	c.initFormCache()
521 14
	if values := c.formCache[key]; len(values) > 0 {
522 14
		return values, true
523
	}
524 14
	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 14
	dicts, _ := c.GetPostFormMap(key)
530 14
	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 14
	c.initFormCache()
537 14
	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 14
	dicts := make(map[string]string)
543 14
	exist := false
544
	for k, v := range m {
545 14
		if i := strings.IndexByte(k, '['); i >= 1 && k[0:i] == key {
546 14
			if j := strings.IndexByte(k[i+1:], ']'); j >= 1 {
547 14
				exist = true
548 14
				dicts[k[i+1:][:j]] = v[0]
549
			}
550
		}
551
	}
552 14
	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 14
	if c.Request.MultipartForm == nil {
558 14
		if err := c.Request.ParseMultipartForm(c.engine.MaxMultipartMemory); err != nil {
559 14
			return nil, err
560
		}
561
	}
562 14
	f, fh, err := c.Request.FormFile(name)
563 14
	if err != nil {
564 0
		return nil, err
565
	}
566 14
	f.Close()
567 14
	return fh, err
568
}
569

570
// MultipartForm is the parsed multipart form, including file uploads.
571
func (c *Context) MultipartForm() (*multipart.Form, error) {
572 14
	err := c.Request.ParseMultipartForm(c.engine.MaxMultipartMemory)
573 14
	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 14
	src, err := file.Open()
579 14
	if err != nil {
580 14
		return err
581
	}
582 14
	defer src.Close()
583

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

590 14
	_, err = io.Copy(out, src)
591 14
	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 14
	b := binding.Default(c.Request.Method, c.ContentType())
604 14
	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 14
	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 14
	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 14
	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 14
	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 14
	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 14
	if err := c.ShouldBindUri(obj); err != nil {
636 14
		c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) // nolint: errcheck
637 14
		return err
638
	}
639 14
	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 14
	if err := c.ShouldBindWith(obj, b); err != nil {
647 14
		c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) // nolint: errcheck
648 14
		return err
649
	}
650 14
	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 14
	b := binding.Default(c.Request.Method, c.ContentType())
663 14
	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 14
	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 14
	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 14
	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 14
	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 14
	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 14
	m := make(map[string][]string)
694
	for _, v := range c.Params {
695 14
		m[v.Key] = []string{v.Value}
696
	}
697 14
	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 14
	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 14
	var body []byte
713 14
	if cb, ok := c.Get(BodyBytesKey); ok {
714 14
		if cbb, ok := cb.([]byte); ok {
715 14
			body = cbb
716
		}
717
	}
718 14
	if body == nil {
719 14
		body, err = ioutil.ReadAll(c.Request.Body)
720 14
		if err != nil {
721 0
			return err
722
		}
723 14
		c.Set(BodyBytesKey, body)
724
	}
725 14
	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 14
	if c.engine.ForwardedByClientIP {
733 14
		clientIP := c.requestHeader("X-Forwarded-For")
734 14
		clientIP = strings.TrimSpace(strings.Split(clientIP, ",")[0])
735 14
		if clientIP == "" {
736 14
			clientIP = strings.TrimSpace(c.requestHeader("X-Real-Ip"))
737
		}
738 14
		if clientIP != "" {
739 14
			return clientIP
740
		}
741
	}
742

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

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

753 14
	return ""
754
}
755

756
// ContentType returns the Content-Type header of the request.
757
func (c *Context) ContentType() string {
758 14
	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 14
	if strings.Contains(strings.ToLower(c.requestHeader("Connection")), "upgrade") &&
765 14
		strings.EqualFold(c.requestHeader("Upgrade"), "websocket") {
766 14
		return true
767
	}
768 14
	return false
769
}
770

771
func (c *Context) requestHeader(key string) string {
772 14
	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 14
	switch {
782 14
	case status >= 100 && status <= 199:
783 14
		return false
784 14
	case status == http.StatusNoContent:
785 14
		return false
786 14
	case status == http.StatusNotModified:
787 14
		return false
788
	}
789 14
	return true
790
}
791

792
// Status sets the HTTP response code.
793
func (c *Context) Status(code int) {
794 14
	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 14
	if value == "" {
802 14
		c.Writer.Header().Del(key)
803 14
		return
804
	}
805 14
	c.Writer.Header().Set(key, value)
806
}
807

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

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

818
// SetSameSite with cookie
819
func (c *Context) SetSameSite(samesite http.SameSite) {
820 14
	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 14
	if path == "" {
828 14
		path = "/"
829
	}
830 14
	http.SetCookie(c.Writer, &http.Cookie{
831 14
		Name:     name,
832 14
		Value:    url.QueryEscape(value),
833 14
		MaxAge:   maxAge,
834 14
		Path:     path,
835 14
		Domain:   domain,
836 14
		SameSite: c.sameSite,
837 14
		Secure:   secure,
838 14
		HttpOnly: httpOnly,
839 14
	})
840
}
841

842
// Cookie returns the named cookie provided in the request or
843
// ErrNoCookie if not found. And return the named cookie is unescaped.
844
// If multiple cookies match the given name, only one cookie will
845
// be returned.
846
func (c *Context) Cookie(name string) (string, error) {
847 14
	cookie, err := c.Request.Cookie(name)
848 14
	if err != nil {
849 14
		return "", err
850
	}
851 14
	val, _ := url.QueryUnescape(cookie.Value)
852 14
	return val, nil
853
}
854

855
// Render writes the response headers and calls render.Render to render data.
856
func (c *Context) Render(code int, r render.Render) {
857 14
	c.Status(code)
858

859 14
	if !bodyAllowedForStatus(code) {
860 14
		r.WriteContentType(c.Writer)
861 14
		c.Writer.WriteHeaderNow()
862 14
		return
863
	}
864

865 14
	if err := r.Render(c.Writer); err != nil {
866 14
		panic(err)
867
	}
868
}
869

870
// HTML renders the HTTP template specified by its file name.
871
// It also updates the HTTP code and sets the Content-Type as "text/html".
872
// See http://golang.org/doc/articles/wiki/
873
func (c *Context) HTML(code int, name string, obj interface{}) {
874 14
	instance := c.engine.HTMLRender.Instance(name, obj)
875 14
	c.Render(code, instance)
876
}
877

878
// IndentedJSON serializes the given struct as pretty JSON (indented + endlines) into the response body.
879
// It also sets the Content-Type as "application/json".
880
// WARNING: we recommend to use this only for development purposes since printing pretty JSON is
881
// more CPU and bandwidth consuming. Use Context.JSON() instead.
882
func (c *Context) IndentedJSON(code int, obj interface{}) {
883 14
	c.Render(code, render.IndentedJSON{Data: obj})
884
}
885

886
// SecureJSON serializes the given struct as Secure JSON into the response body.
887
// Default prepends "while(1)," to response body if the given struct is array values.
888
// It also sets the Content-Type as "application/json".
889
func (c *Context) SecureJSON(code int, obj interface{}) {
890 14
	c.Render(code, render.SecureJSON{Prefix: c.engine.secureJSONPrefix, Data: obj})
891
}
892

893
// JSONP serializes the given struct as JSON into the response body.
894
// It adds padding to response body to request data from a server residing in a different domain than the client.
895
// It also sets the Content-Type as "application/javascript".
896
func (c *Context) JSONP(code int, obj interface{}) {
897 14
	callback := c.DefaultQuery("callback", "")
898 14
	if callback == "" {
899 14
		c.Render(code, render.JSON{Data: obj})
900 14
		return
901
	}
902 14
	c.Render(code, render.JsonpJSON{Callback: callback, Data: obj})
903
}
904

905
// JSON serializes the given struct as JSON into the response body.
906
// It also sets the Content-Type as "application/json".
907
func (c *Context) JSON(code int, obj interface{}) {
908 14
	c.Render(code, render.JSON{Data: obj})
909
}
910

911
// AsciiJSON serializes the given struct as JSON into the response body with unicode to ASCII string.
912
// It also sets the Content-Type as "application/json".
913
func (c *Context) AsciiJSON(code int, obj interface{}) {
914 14
	c.Render(code, render.AsciiJSON{Data: obj})
915
}
916

917
// PureJSON serializes the given struct as JSON into the response body.
918
// PureJSON, unlike JSON, does not replace special html characters with their unicode entities.
919
func (c *Context) PureJSON(code int, obj interface{}) {
920 14
	c.Render(code, render.PureJSON{Data: obj})
921
}
922

923
// XML serializes the given struct as XML into the response body.
924
// It also sets the Content-Type as "application/xml".
925
func (c *Context) XML(code int, obj interface{}) {
926 14
	c.Render(code, render.XML{Data: obj})
927
}
928

929
// YAML serializes the given struct as YAML into the response body.
930
func (c *Context) YAML(code int, obj interface{}) {
931 14
	c.Render(code, render.YAML{Data: obj})
932
}
933

934
// ProtoBuf serializes the given struct as ProtoBuf into the response body.
935
func (c *Context) ProtoBuf(code int, obj interface{}) {
936 14
	c.Render(code, render.ProtoBuf{Data: obj})
937
}
938

939
// String writes the given string into the response body.
940
func (c *Context) String(code int, format string, values ...interface{}) {
941 14
	c.Render(code, render.String{Format: format, Data: values})
942
}
943

944
// Redirect returns a HTTP redirect to the specific location.
945
func (c *Context) Redirect(code int, location string) {
946
	c.Render(-1, render.Redirect{
947 14
		Code:     code,
948 14
		Location: location,
949 14
		Request:  c.Request,
950 14
	})
951
}
952

953
// Data writes some data into the body stream and updates the HTTP code.
954
func (c *Context) Data(code int, contentType string, data []byte) {
955
	c.Render(code, render.Data{
956 14
		ContentType: contentType,
957 14
		Data:        data,
958 14
	})
959
}
960

961
// DataFromReader writes the specified reader into the body stream and updates the HTTP code.
962
func (c *Context) DataFromReader(code int, contentLength int64, contentType string, reader io.Reader, extraHeaders map[string]string) {
963
	c.Render(code, render.Reader{
964 14
		Headers:       extraHeaders,
965 14
		ContentType:   contentType,
966 14
		ContentLength: contentLength,
967 14
		Reader:        reader,
968 14
	})
969
}
970

971
// File writes the specified file into the body stream in an efficient way.
972
func (c *Context) File(filepath string) {
973 14
	http.ServeFile(c.Writer, c.Request, filepath)
974
}
975

976
// FileFromFS writes the specified file from http.FileSystem into the body stream in an efficient way.
977
func (c *Context) FileFromFS(filepath string, fs http.FileSystem) {
978 14
	defer func(old string) {
979 14
		c.Request.URL.Path = old
980 14
	}(c.Request.URL.Path)
981

982 14
	c.Request.URL.Path = filepath
983

984 14
	http.FileServer(fs).ServeHTTP(c.Writer, c.Request)
985
}
986

987
// FileAttachment writes the specified file into the body stream in an efficient way
988
// On the client side, the file will typically be downloaded with the given filename
989
func (c *Context) FileAttachment(filepath, filename string) {
990 14
	c.Writer.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
991 14
	http.ServeFile(c.Writer, c.Request, filepath)
992
}
993

994
// SSEvent writes a Server-Sent Event into the body stream.
995
func (c *Context) SSEvent(name string, message interface{}) {
996
	c.Render(-1, sse.Event{
997 14
		Event: name,
998 14
		Data:  message,
999 14
	})
1000
}
1001

1002
// Stream sends a streaming response and returns a boolean
1003
// indicates "Is client disconnected in middle of stream"
1004
func (c *Context) Stream(step func(w io.Writer) bool) bool {
1005 14
	w := c.Writer
1006 14
	clientGone := w.CloseNotify()
1007
	for {
1008 14
		select {
1009 14
		case <-clientGone:
1010 14
			return true
1011 14
		default:
1012 14
			keepOpen := step(w)
1013 14
			w.Flush()
1014 14
			if !keepOpen {
1015 14
				return false
1016
			}
1017
		}
1018
	}
1019
}
1020

1021
/************************************/
1022
/******** CONTENT NEGOTIATION *******/
1023
/************************************/
1024

1025
// Negotiate contains all negotiations data.
1026
type Negotiate struct {
1027
	Offered  []string
1028
	HTMLName string
1029
	HTMLData interface{}
1030
	JSONData interface{}
1031
	XMLData  interface{}
1032
	YAMLData interface{}
1033
	Data     interface{}
1034
}
1035

1036
// Negotiate calls different Render according acceptable Accept format.
1037
func (c *Context) Negotiate(code int, config Negotiate) {
1038 14
	switch c.NegotiateFormat(config.Offered...) {
1039 14
	case binding.MIMEJSON:
1040 14
		data := chooseData(config.JSONData, config.Data)
1041 14
		c.JSON(code, data)
1042

1043 14
	case binding.MIMEHTML:
1044 14
		data := chooseData(config.HTMLData, config.Data)
1045 14
		c.HTML(code, config.HTMLName, data)
1046

1047 14
	case binding.MIMEXML:
1048 14
		data := chooseData(config.XMLData, config.Data)
1049 14
		c.XML(code, data)
1050

1051 0
	case binding.MIMEYAML:
1052 0
		data := chooseData(config.YAMLData, config.Data)
1053 0
		c.YAML(code, data)
1054

1055 14
	default:
1056 14
		c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server")) // nolint: errcheck
1057
	}
1058
}
1059

1060
// NegotiateFormat returns an acceptable Accept format.
1061
func (c *Context) NegotiateFormat(offered ...string) string {
1062 14
	assert1(len(offered) > 0, "you must provide at least one offer")
1063

1064 14
	if c.Accepted == nil {
1065 14
		c.Accepted = parseAccept(c.requestHeader("Accept"))
1066
	}
1067 14
	if len(c.Accepted) == 0 {
1068 14
		return offered[0]
1069
	}
1070
	for _, accepted := range c.Accepted {
1071
		for _, offer := range offered {
1072
			// According to RFC 2616 and RFC 2396, non-ASCII characters are not allowed in headers,
1073
			// therefore we can just iterate over the string without casting it into []rune
1074 14
			i := 0
1075
			for ; i < len(accepted); i++ {
1076 14
				if accepted[i] == '*' || offer[i] == '*' {
1077 14
					return offer
1078
				}
1079 14
				if accepted[i] != offer[i] {
1080 14
					break
1081
				}
1082
			}
1083 14
			if i == len(accepted) {
1084 14
				return offer
1085
			}
1086
		}
1087
	}
1088 14
	return ""
1089
}
1090

1091
// SetAccepted sets Accept header data.
1092
func (c *Context) SetAccepted(formats ...string) {
1093 14
	c.Accepted = formats
1094
}
1095

1096
/************************************/
1097
/***** GOLANG.ORG/X/NET/CONTEXT *****/
1098
/************************************/
1099

1100
// Deadline always returns that there is no deadline (ok==false),
1101
// maybe you want to use Request.Context().Deadline() instead.
1102
func (c *Context) Deadline() (deadline time.Time, ok bool) {
1103 14
	return
1104
}
1105

1106
// Done always returns nil (chan which will wait forever),
1107
// if you want to abort your work when the connection was closed
1108
// you should use Request.Context().Done() instead.
1109
func (c *Context) Done() <-chan struct{} {
1110 14
	return nil
1111
}
1112

1113
// Err always returns nil, maybe you want to use Request.Context().Err() instead.
1114
func (c *Context) Err() error {
1115 14
	return nil
1116
}
1117

1118
// Value returns the value associated with this context for key, or nil
1119
// if no value is associated with key. Successive calls to Value with
1120
// the same key returns the same result.
1121
func (c *Context) Value(key interface{}) interface{} {
1122 14
	if key == 0 {
1123 14
		return c.Request
1124
	}
1125 14
	if keyAsString, ok := key.(string); ok {
1126 14
		val, _ := c.Get(keyAsString)
1127 14
		return val
1128
	}
1129 14
	return nil
1130
}

Read our documentation on viewing source code .

Loading