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.
20 "github.com/gin-contrib/sse"
21 "github.com/gin-gonic/gin/binding"
22 "github.com/gin-gonic/gin/render"
25 // Content-Type MIME of the most common data formats.
27 MIMEJSON = binding.MIMEJSON
28 MIMEHTML = binding.MIMEHTML
29 MIMEXML = binding.MIMEXML
30 MIMEXML2 = binding.MIMEXML2
31 MIMEPlain = binding.MIMEPlain
32 MIMEPOSTForm = binding.MIMEPOSTForm
33 MIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm
34 BodyBytesKey = "_gin-gonic/gin/bodybyteskey"
37 const abortIndex int8 = math.MaxInt8 / 2
39 // Context is the most important part of gin. It allows us to pass variables between middleware,
40 // manage the flow, validate the JSON of a request and render a JSON response for example.
42 writermem responseWriter
47 handlers HandlersChain
52 // Keys is a key/value pair exclusively for the context of each request.
53 Keys map[string]interface{}
55 // Errors is a list of errors attached to all the handlers/middlewares who used this context.
58 // Accepted defines a list of manually accepted formats for content negotiation.
62 /************************************/
63 /********** CONTEXT CREATION ********/
64 /************************************/
66 func (c *Context) reset() {
67 c.Writer = &c.writermem
68 c.Params = c.Params[0:0]
72 c.Errors = c.Errors[0:0]
76 // Copy returns a copy of the current context that can be safely used outside the request's scope.
77 // This has to be used when the context has to be passed to a goroutine.
78 func (c *Context) Copy() *Context {
80 cp.writermem.ResponseWriter = nil
81 cp.Writer = &cp.writermem
87 // HandlerName returns the main handler's name. For example if the handler is "handleGetUsers()",
88 // this function will return "main.handleGetUsers".
89 func (c *Context) HandlerName() string {
90 return nameOfFunction(c.handlers.Last())
93 // Handler returns the main handler.
94 func (c *Context) Handler() HandlerFunc {
95 return c.handlers.Last()
98 /************************************/
99 /*********** FLOW CONTROL ***********/
100 /************************************/
102 // Next should be used only inside middleware.
103 // It executes the pending handlers in the chain inside the calling handler.
104 // See example in GitHub.
105 func (c *Context) Next() {
107 for s := int8(len(c.handlers)); c.index < s; c.index++ {
108 c.handlers[c.index](c)
112 // IsAborted returns true if the current context was aborted.
113 func (c *Context) IsAborted() bool {
114 return c.index >= abortIndex
117 // Abort prevents pending handlers from being called. Note that this will not stop the current handler.
118 // Let's say you have an authorization middleware that validates that the current request is authorized.
119 // If the authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers
120 // for this request are not called.
121 func (c *Context) Abort() {
125 // AbortWithStatus calls `Abort()` and writes the headers with the specified status code.
126 // For example, a failed attempt to authenticate a request could use: context.AbortWithStatus(401).
127 func (c *Context) AbortWithStatus(code int) {
129 c.Writer.WriteHeaderNow()
133 // AbortWithStatusJSON calls `Abort()` and then `JSON` internally.
134 // This method stops the chain, writes the status code and return a JSON body.
135 // It also sets the Content-Type as "application/json".
136 func (c *Context) AbortWithStatusJSON(code int, jsonObj interface{}) {
138 c.JSON(code, jsonObj)
141 // AbortWithError calls `AbortWithStatus()` and `Error()` internally.
142 // This method stops the chain, writes the status code and pushes the specified error to `c.Errors`.
143 // See Context.Error() for more details.
144 func (c *Context) AbortWithError(code int, err error) *Error {
145 c.AbortWithStatus(code)
149 /************************************/
150 /********* ERROR MANAGEMENT *********/
151 /************************************/
153 // Error attaches an error to the current context. The error is pushed to a list of errors.
154 // It's a good idea to call Error for each error that occurred during the resolution of a request.
155 // A middleware can be used to collect all the errors and push them to a database together,
156 // print a log, or append it in the HTTP response.
157 // Error will panic if err is nil.
158 func (c *Context) Error(err error) *Error {
163 parsedError, ok := err.(*Error)
165 parsedError = &Error{
167 Type: ErrorTypePrivate,
171 c.Errors = append(c.Errors, parsedError)
175 /************************************/
176 /******** METADATA MANAGEMENT********/
177 /************************************/
179 // Set is used to store a new key/value pair exclusively for this context.
180 // It also lazy initializes c.Keys if it was not used previously.
181 func (c *Context) Set(key string, value interface{}) {
183 c.Keys = make(map[string]interface{})
188 // Get returns the value for the given key, ie: (value, true).
189 // If the value does not exists it returns (nil, false)
190 func (c *Context) Get(key string) (value interface{}, exists bool) {
191 value, exists = c.Keys[key]
195 // MustGet returns the value for the given key if it exists, otherwise it panics.
196 func (c *Context) MustGet(key string) interface{} {
197 if value, exists := c.Get(key); exists {
200 panic("Key \"" + key + "\" does not exist")
203 // GetString returns the value associated with the key as a string.
204 func (c *Context) GetString(key string) (s string) {
205 if val, ok := c.Get(key); ok && val != nil {
211 // GetBool returns the value associated with the key as a boolean.
212 func (c *Context) GetBool(key string) (b bool) {
213 if val, ok := c.Get(key); ok && val != nil {
219 // GetInt returns the value associated with the key as an integer.
220 func (c *Context) GetInt(key string) (i int) {
221 if val, ok := c.Get(key); ok && val != nil {
227 // GetInt64 returns the value associated with the key as an integer.
228 func (c *Context) GetInt64(key string) (i64 int64) {
229 if val, ok := c.Get(key); ok && val != nil {
235 // GetFloat64 returns the value associated with the key as a float64.
236 func (c *Context) GetFloat64(key string) (f64 float64) {
237 if val, ok := c.Get(key); ok && val != nil {
238 f64, _ = val.(float64)
243 // GetTime returns the value associated with the key as time.
244 func (c *Context) GetTime(key string) (t time.Time) {
245 if val, ok := c.Get(key); ok && val != nil {
246 t, _ = val.(time.Time)
251 // GetDuration returns the value associated with the key as a duration.
252 func (c *Context) GetDuration(key string) (d time.Duration) {
253 if val, ok := c.Get(key); ok && val != nil {
254 d, _ = val.(time.Duration)
259 // GetStringSlice returns the value associated with the key as a slice of strings.
260 func (c *Context) GetStringSlice(key string) (ss []string) {
261 if val, ok := c.Get(key); ok && val != nil {
262 ss, _ = val.([]string)
267 // GetStringMap returns the value associated with the key as a map of interfaces.
268 func (c *Context) GetStringMap(key string) (sm map[string]interface{}) {
269 if val, ok := c.Get(key); ok && val != nil {
270 sm, _ = val.(map[string]interface{})
275 // GetStringMapString returns the value associated with the key as a map of strings.
276 func (c *Context) GetStringMapString(key string) (sms map[string]string) {
277 if val, ok := c.Get(key); ok && val != nil {
278 sms, _ = val.(map[string]string)
283 // GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.
284 func (c *Context) GetStringMapStringSlice(key string) (smss map[string][]string) {
285 if val, ok := c.Get(key); ok && val != nil {
286 smss, _ = val.(map[string][]string)
291 /************************************/
292 /************ INPUT DATA ************/
293 /************************************/
295 // Param returns the value of the URL param.
296 // It is a shortcut for c.Params.ByName(key)
297 // router.GET("/user/:id", func(c *gin.Context) {
298 // // a GET request to /user/john
299 // id := c.Param("id") // id == "john"
301 func (c *Context) Param(key string) string {
302 return c.Params.ByName(key)
305 // Query returns the keyed url query value if it exists,
306 // otherwise it returns an empty string `("")`.
307 // It is shortcut for `c.Request.URL.Query().Get(key)`
308 // GET /path?id=1234&name=Manu&value=
309 // c.Query("id") == "1234"
310 // c.Query("name") == "Manu"
311 // c.Query("value") == ""
312 // c.Query("wtf") == ""
313 func (c *Context) Query(key string) string {
314 value, _ := c.GetQuery(key)
318 // DefaultQuery returns the keyed url query value if it exists,
319 // otherwise it returns the specified defaultValue string.
320 // See: Query() and GetQuery() for further information.
321 // GET /?name=Manu&lastname=
322 // c.DefaultQuery("name", "unknown") == "Manu"
323 // c.DefaultQuery("id", "none") == "none"
324 // c.DefaultQuery("lastname", "none") == ""
325 func (c *Context) DefaultQuery(key, defaultValue string) string {
326 if value, ok := c.GetQuery(key); ok {
332 // GetQuery is like Query(), it returns the keyed url query value
333 // if it exists `(value, true)` (even when the value is an empty string),
334 // otherwise it returns `("", false)`.
335 // It is shortcut for `c.Request.URL.Query().Get(key)`
336 // GET /?name=Manu&lastname=
337 // ("Manu", true) == c.GetQuery("name")
338 // ("", false) == c.GetQuery("id")
339 // ("", true) == c.GetQuery("lastname")
340 func (c *Context) GetQuery(key string) (string, bool) {
341 if values, ok := c.GetQueryArray(key); ok {
347 // QueryArray returns a slice of strings for a given query key.
348 // The length of the slice depends on the number of params with the given key.
349 func (c *Context) QueryArray(key string) []string {
350 values, _ := c.GetQueryArray(key)
354 // GetQueryArray returns a slice of strings for a given query key, plus
355 // a boolean value whether at least one value exists for the given key.
356 func (c *Context) GetQueryArray(key string) ([]string, bool) {
357 if values, ok := c.Request.URL.Query()[key]; ok && len(values) > 0 {
360 return []string{}, false
363 // QueryMap returns a map for a given query key.
364 func (c *Context) QueryMap(key string) map[string]string {
365 dicts, _ := c.GetQueryMap(key)
369 // GetQueryMap returns a map for a given query key, plus a boolean value
370 // whether at least one value exists for the given key.
371 func (c *Context) GetQueryMap(key string) (map[string]string, bool) {
372 return c.get(c.Request.URL.Query(), key)
375 // PostForm returns the specified key from a POST urlencoded form or multipart form
376 // when it exists, otherwise it returns an empty string `("")`.
377 func (c *Context) PostForm(key string) string {
378 value, _ := c.GetPostForm(key)
382 // DefaultPostForm returns the specified key from a POST urlencoded form or multipart form
383 // when it exists, otherwise it returns the specified defaultValue string.
384 // See: PostForm() and GetPostForm() for further information.
385 func (c *Context) DefaultPostForm(key, defaultValue string) string {
386 if value, ok := c.GetPostForm(key); ok {
392 // GetPostForm is like PostForm(key). It returns the specified key from a POST urlencoded
393 // form or multipart form when it exists `(value, true)` (even when the value is an empty string),
394 // otherwise it returns ("", false).
395 // For example, during a PATCH request to update the user's email:
396 // email=mail@example.com --> ("mail@example.com", true) := GetPostForm("email") // set email to "mail@example.com"
397 // email= --> ("", true) := GetPostForm("email") // set email to ""
398 // --> ("", false) := GetPostForm("email") // do nothing with email
399 func (c *Context) GetPostForm(key string) (string, bool) {
400 if values, ok := c.GetPostFormArray(key); ok {
406 // PostFormArray returns a slice of strings for a given form key.
407 // The length of the slice depends on the number of params with the given key.
408 func (c *Context) PostFormArray(key string) []string {
409 values, _ := c.GetPostFormArray(key)
413 // GetPostFormArray returns a slice of strings for a given form key, plus
414 // a boolean value whether at least one value exists for the given key.
415 func (c *Context) GetPostFormArray(key string) ([]string, bool) {
418 req.ParseMultipartForm(c.engine.MaxMultipartMemory)
419 if values := req.PostForm[key]; len(values) > 0 {
422 if req.MultipartForm != nil && req.MultipartForm.File != nil {
423 if values := req.MultipartForm.Value[key]; len(values) > 0 {
427 return []string{}, false
430 // PostFormMap returns a map for a given form key.
431 func (c *Context) PostFormMap(key string) map[string]string {
432 dicts, _ := c.GetPostFormMap(key)
436 // GetPostFormMap returns a map for a given form key, plus a boolean value
437 // whether at least one value exists for the given key.
438 func (c *Context) GetPostFormMap(key string) (map[string]string, bool) {
441 req.ParseMultipartForm(c.engine.MaxMultipartMemory)
442 dicts, exist := c.get(req.PostForm, key)
444 if !exist && req.MultipartForm != nil && req.MultipartForm.File != nil {
445 dicts, exist = c.get(req.MultipartForm.Value, key)
451 // get is an internal method and returns a map which satisfy conditions.
452 func (c *Context) get(m map[string][]string, key string) (map[string]string, bool) {
453 dicts := make(map[string]string)
455 for k, v := range m {
456 if i := strings.IndexByte(k, '['); i >= 1 && k[0:i] == key {
457 if j := strings.IndexByte(k[i+1:], ']'); j >= 1 {
459 dicts[k[i+1:][:j]] = v[0]
466 // FormFile returns the first file for the provided form key.
467 func (c *Context) FormFile(name string) (*multipart.FileHeader, error) {
468 _, fh, err := c.Request.FormFile(name)
472 // MultipartForm is the parsed multipart form, including file uploads.
473 func (c *Context) MultipartForm() (*multipart.Form, error) {
474 err := c.Request.ParseMultipartForm(c.engine.MaxMultipartMemory)
475 return c.Request.MultipartForm, err
478 // SaveUploadedFile uploads the form file to specific dst.
479 func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error {
480 src, err := file.Open()
486 out, err := os.Create(dst)
496 // Bind checks the Content-Type to select a binding engine automatically,
497 // Depending the "Content-Type" header different bindings are used:
498 // "application/json" --> JSON binding
499 // "application/xml" --> XML binding
500 // otherwise --> returns an error.
501 // It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input.
502 // It decodes the json payload into the struct specified as a pointer.
503 // It writes a 400 error and sets Content-Type header "text/plain" in the response if input is not valid.
504 func (c *Context) Bind(obj interface{}) error {
505 b := binding.Default(c.Request.Method, c.ContentType())
506 return c.MustBindWith(obj, b)
509 // BindJSON is a shortcut for c.MustBindWith(obj, binding.JSON).
510 func (c *Context) BindJSON(obj interface{}) error {
511 return c.MustBindWith(obj, binding.JSON)
514 // BindQuery is a shortcut for c.MustBindWith(obj, binding.Query).
515 func (c *Context) BindQuery(obj interface{}) error {
516 return c.MustBindWith(obj, binding.Query)
519 // MustBindWith binds the passed struct pointer using the specified binding engine.
520 // It will abort the request with HTTP 400 if any error ocurrs.
521 // See the binding package.
522 func (c *Context) MustBindWith(obj interface{}, b binding.Binding) (err error) {
523 if err = c.ShouldBindWith(obj, b); err != nil {
524 c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind)
530 // ShouldBind checks the Content-Type to select a binding engine automatically,
531 // Depending the "Content-Type" header different bindings are used:
532 // "application/json" --> JSON binding
533 // "application/xml" --> XML binding
534 // otherwise --> returns an error
535 // It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input.
536 // It decodes the json payload into the struct specified as a pointer.
537 // Like c.Bind() but this method does not set the response status code to 400 and abort if the json is not valid.
538 func (c *Context) ShouldBind(obj interface{}) error {
539 b := binding.Default(c.Request.Method, c.ContentType())
540 return c.ShouldBindWith(obj, b)
543 // ShouldBindJSON is a shortcut for c.ShouldBindWith(obj, binding.JSON).
544 func (c *Context) ShouldBindJSON(obj interface{}) error {
545 return c.ShouldBindWith(obj, binding.JSON)
548 // ShouldBindQuery is a shortcut for c.ShouldBindWith(obj, binding.Query).
549 func (c *Context) ShouldBindQuery(obj interface{}) error {
550 return c.ShouldBindWith(obj, binding.Query)
553 // ShouldBindWith binds the passed struct pointer using the specified binding engine.
554 // See the binding package.
555 func (c *Context) ShouldBindWith(obj interface{}, b binding.Binding) error {
556 return b.Bind(c.Request, obj)
559 // ShouldBindBodyWith is similar with ShouldBindWith, but it stores the request
560 // body into the context, and reuse when it is called again.
562 // NOTE: This method reads the body before binding. So you should use
563 // ShouldBindWith for better performance if you need to call only once.
564 func (c *Context) ShouldBindBodyWith(
565 obj interface{}, bb binding.BindingBody,
568 if cb, ok := c.Get(BodyBytesKey); ok {
569 if cbb, ok := cb.([]byte); ok {
574 body, err = ioutil.ReadAll(c.Request.Body)
578 c.Set(BodyBytesKey, body)
580 return bb.BindBody(body, obj)
583 // ClientIP implements a best effort algorithm to return the real client IP, it parses
584 // X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy.
585 // Use X-Forwarded-For before X-Real-Ip as nginx uses X-Real-Ip with the proxy's IP.
586 func (c *Context) ClientIP() string {
587 if c.engine.ForwardedByClientIP {
588 clientIP := c.requestHeader("X-Forwarded-For")
589 clientIP = strings.TrimSpace(strings.Split(clientIP, ",")[0])
591 clientIP = strings.TrimSpace(c.requestHeader("X-Real-Ip"))
598 if c.engine.AppEngine {
599 if addr := c.requestHeader("X-Appengine-Remote-Addr"); addr != "" {
604 if ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr)); err == nil {
611 // ContentType returns the Content-Type header of the request.
612 func (c *Context) ContentType() string {
613 return filterFlags(c.requestHeader("Content-Type"))
616 // IsWebsocket returns true if the request headers indicate that a websocket
617 // handshake is being initiated by the client.
618 func (c *Context) IsWebsocket() bool {
619 if strings.Contains(strings.ToLower(c.requestHeader("Connection")), "upgrade") &&
620 strings.ToLower(c.requestHeader("Upgrade")) == "websocket" {
626 func (c *Context) requestHeader(key string) string {
627 return c.Request.Header.Get(key)
630 /************************************/
631 /******** RESPONSE RENDERING ********/
632 /************************************/
634 // bodyAllowedForStatus is a copy of http.bodyAllowedForStatus non-exported function.
635 func bodyAllowedForStatus(status int) bool {
637 case status >= 100 && status <= 199:
639 case status == http.StatusNoContent:
641 case status == http.StatusNotModified:
647 // Status sets the HTTP response code.
648 func (c *Context) Status(code int) {
649 c.writermem.WriteHeader(code)
652 // Header is a intelligent shortcut for c.Writer.Header().Set(key, value).
653 // It writes a header in the response.
654 // If value == "", this method removes the header `c.Writer.Header().Del(key)`
655 func (c *Context) Header(key, value string) {
657 c.Writer.Header().Del(key)
659 c.Writer.Header().Set(key, value)
663 // GetHeader returns value from request headers.
664 func (c *Context) GetHeader(key string) string {
665 return c.requestHeader(key)
668 // GetRawData return stream data.
669 func (c *Context) GetRawData() ([]byte, error) {
670 return ioutil.ReadAll(c.Request.Body)
673 // SetCookie adds a Set-Cookie header to the ResponseWriter's headers.
674 // The provided cookie must have a valid Name. Invalid cookies may be
676 func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool) {
680 http.SetCookie(c.Writer, &http.Cookie{
682 Value: url.QueryEscape(value),
691 // Cookie returns the named cookie provided in the request or
692 // ErrNoCookie if not found. And return the named cookie is unescaped.
693 // If multiple cookies match the given name, only one cookie will
695 func (c *Context) Cookie(name string) (string, error) {
696 cookie, err := c.Request.Cookie(name)
700 val, _ := url.QueryUnescape(cookie.Value)
704 func (c *Context) Render(code int, r render.Render) {
707 if !bodyAllowedForStatus(code) {
708 r.WriteContentType(c.Writer)
709 c.Writer.WriteHeaderNow()
713 if err := r.Render(c.Writer); err != nil {
718 // HTML renders the HTTP template specified by its file name.
719 // It also updates the HTTP code and sets the Content-Type as "text/html".
720 // See http://golang.org/doc/articles/wiki/
721 func (c *Context) HTML(code int, name string, obj interface{}) {
722 instance := c.engine.HTMLRender.Instance(name, obj)
723 c.Render(code, instance)
726 // IndentedJSON serializes the given struct as pretty JSON (indented + endlines) into the response body.
727 // It also sets the Content-Type as "application/json".
728 // WARNING: we recommend to use this only for development purposes since printing pretty JSON is
729 // more CPU and bandwidth consuming. Use Context.JSON() instead.
730 func (c *Context) IndentedJSON(code int, obj interface{}) {
731 c.Render(code, render.IndentedJSON{Data: obj})
734 // SecureJSON serializes the given struct as Secure JSON into the response body.
735 // Default prepends "while(1)," to response body if the given struct is array values.
736 // It also sets the Content-Type as "application/json".
737 func (c *Context) SecureJSON(code int, obj interface{}) {
738 c.Render(code, render.SecureJSON{Prefix: c.engine.secureJsonPrefix, Data: obj})
741 // JSONP serializes the given struct as JSON into the response body.
742 // It add padding to response body to request data from a server residing in a different domain than the client.
743 // It also sets the Content-Type as "application/javascript".
744 func (c *Context) JSONP(code int, obj interface{}) {
745 callback := c.DefaultQuery("callback", "")
747 c.Render(code, render.JSON{Data: obj})
749 c.Render(code, render.JsonpJSON{Callback: callback, Data: obj})
753 // JSON serializes the given struct as JSON into the response body.
754 // It also sets the Content-Type as "application/json".
755 func (c *Context) JSON(code int, obj interface{}) {
756 c.Render(code, render.JSON{Data: obj})
759 // AsciiJSON serializes the given struct as JSON into the response body with unicode to ASCII string.
760 // It also sets the Content-Type as "application/json".
761 func (c *Context) AsciiJSON(code int, obj interface{}) {
762 c.Render(code, render.AsciiJSON{Data: obj})
765 // XML serializes the given struct as XML into the response body.
766 // It also sets the Content-Type as "application/xml".
767 func (c *Context) XML(code int, obj interface{}) {
768 c.Render(code, render.XML{Data: obj})
771 // YAML serializes the given struct as YAML into the response body.
772 func (c *Context) YAML(code int, obj interface{}) {
773 c.Render(code, render.YAML{Data: obj})
776 // String writes the given string into the response body.
777 func (c *Context) String(code int, format string, values ...interface{}) {
778 c.Render(code, render.String{Format: format, Data: values})
781 // Redirect returns a HTTP redirect to the specific location.
782 func (c *Context) Redirect(code int, location string) {
783 c.Render(-1, render.Redirect{
790 // Data writes some data into the body stream and updates the HTTP code.
791 func (c *Context) Data(code int, contentType string, data []byte) {
792 c.Render(code, render.Data{
793 ContentType: contentType,
798 // DataFromReader writes the specified reader into the body stream and updates the HTTP code.
799 func (c *Context) DataFromReader(code int, contentLength int64, contentType string, reader io.Reader, extraHeaders map[string]string) {
800 c.Render(code, render.Reader{
801 Headers: extraHeaders,
802 ContentType: contentType,
803 ContentLength: contentLength,
808 // File writes the specified file into the body stream in a efficient way.
809 func (c *Context) File(filepath string) {
810 http.ServeFile(c.Writer, c.Request, filepath)
813 // SSEvent writes a Server-Sent Event into the body stream.
814 func (c *Context) SSEvent(name string, message interface{}) {
815 c.Render(-1, sse.Event{
821 func (c *Context) Stream(step func(w io.Writer) bool) {
823 clientGone := w.CloseNotify()
838 /************************************/
839 /******** CONTENT NEGOTIATION *******/
840 /************************************/
842 type Negotiate struct {
851 func (c *Context) Negotiate(code int, config Negotiate) {
852 switch c.NegotiateFormat(config.Offered...) {
853 case binding.MIMEJSON:
854 data := chooseData(config.JSONData, config.Data)
857 case binding.MIMEHTML:
858 data := chooseData(config.HTMLData, config.Data)
859 c.HTML(code, config.HTMLName, data)
861 case binding.MIMEXML:
862 data := chooseData(config.XMLData, config.Data)
866 c.AbortWithError(http.StatusNotAcceptable, errors.New("the accepted formats are not offered by the server"))
870 func (c *Context) NegotiateFormat(offered ...string) string {
871 assert1(len(offered) > 0, "you must provide at least one offer")
873 if c.Accepted == nil {
874 c.Accepted = parseAccept(c.requestHeader("Accept"))
876 if len(c.Accepted) == 0 {
879 for _, accepted := range c.Accepted {
880 for _, offert := range offered {
881 if accepted == offert {
889 func (c *Context) SetAccepted(formats ...string) {
893 /************************************/
894 /***** GOLANG.ORG/X/NET/CONTEXT *****/
895 /************************************/
897 // Deadline returns the time when work done on behalf of this context
898 // should be canceled. Deadline returns ok==false when no deadline is
899 // set. Successive calls to Deadline return the same results.
900 func (c *Context) Deadline() (deadline time.Time, ok bool) {
904 // Done returns a channel that's closed when work done on behalf of this
905 // context should be canceled. Done may return nil if this context can
906 // never be canceled. Successive calls to Done return the same value.
907 func (c *Context) Done() <-chan struct{} {
911 // Err returns a non-nil error value after Done is closed,
912 // successive calls to Err return the same error.
913 // If Done is not yet closed, Err returns nil.
914 // If Done is closed, Err returns a non-nil error explaining why:
915 // Canceled if the context was canceled
916 // or DeadlineExceeded if the context's deadline passed.
917 func (c *Context) Err() error {
921 // Value returns the value associated with this context for key, or nil
922 // if no value is associated with key. Successive calls to Value with
923 // the same key returns the same result.
924 func (c *Context) Value(key interface{}) interface{} {
928 if keyAsString, ok := key.(string); ok {
929 val, _ := c.Get(keyAsString)