code:
r.GET("/tmp", func(c *gin.Context) {
fmt.Println(c.GetHeader("Accept"))
fmt.Println(c.Accepted)
c.String(http.StatusOK, "OK")
})
console:
application/json, text/html
[]
How to use "c.Accepted"?
Comment From: RedCrazyGhost
The 202 (Accepted) status code indicates that the request has been accepted for processing, but the processing has not been completed. The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place. There is no facility in HTTP for re-sending a status code from an asynchronous operation.
The 202 response is intentionally noncommittal. Its purpose is to allow a server to accept a request for some other process (perhaps a batch-oriented process that is only run once per day) without requiring that the user agent's connection to the server persist until the process is completed. The representation sent with this response ought to describe the request's current status and point to (or embed) a status monitor that can provide the user with an estimate of when the request will be fulfilled.
I think it should be used that way
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.POST("/", func(c *gin.Context) {
switch c.NegotiateFormat(gin.MIMEJSON,gin.MIMEXML){
case gin.MIMEJSON:
c.String(http.StatusOK,"json")
case gin.MIMEXML:
c.String(http.StatusOK,"xml")
default:
c.String(http.StatusAccepted,"pls request head accept use application/json or application/xml")
}
})
if err := r.Run(":8080"); err != nil {
panic(err)
}
}
Related source code
// Accepted defines a list of manually accepted formats for content negotiation.
Accepted []string
// SetAccepted sets Accept header data.
func (c *Context) SetAccepted(formats ...string) {
c.Accepted = formats
}
// NegotiateFormat returns an acceptable Accept format.
func (c *Context) NegotiateFormat(offered ...string) string {
assert1(len(offered) > 0, "you must provide at least one offer")
if c.Accepted == nil {
c.Accepted = parseAccept(c.requestHeader("Accept"))
}
if len(c.Accepted) == 0 {
return offered[0]
}
for _, accepted := range c.Accepted {
for _, offer := range offered {
// According to RFC 2616 and RFC 2396, non-ASCII characters are not allowed in headers,
// therefore we can just iterate over the string without casting it into []rune
i := 0
for ; i < len(accepted) && i < len(offer); i++ {
if accepted[i] == '*' || offer[i] == '*' {
return offer
}
if accepted[i] != offer[i] {
break
}
}
if i == len(accepted) {
return offer
}
}
}
return ""
}