Documentation ¶
Index ¶
- Constants
- Variables
- func DisableBindValidation()
- func EnableJsonDecoderDisallowUnknownFields()
- func EnableJsonDecoderUseNumber()
- func IsDebugging() bool
- func Mode() string
- func SetMode(value string)
- func WriteJSON(w ResponseWriter, obj interface{}) error
- type Context
- func (c *Context) Abort()
- func (c *Context) AbortWithError(code int, err error) *Error
- func (c *Context) AbortWithStatus(code int)
- func (c *Context) AbortWithStatusJSON(code int, jsonObj interface{})
- func (c *Context) AddParam(key, value string)
- func (c *Context) BindUri(obj interface{}) error
- func (c *Context) ClientIP() string
- func (c *Context) ContentType() string
- func (c *Context) Copy() *Context
- func (c *Context) Data(code int, contentType string, data []byte)
- func (c *Context) Error(err error) *Error
- func (c *Context) FullPath() string
- func (c *Context) Get(key string) (value interface{}, exists bool)
- func (c *Context) GetBool(key string) (b bool)
- func (c *Context) GetDuration(key string) (d time.Duration)
- func (c *Context) GetFloat64(key string) (f64 float64)
- func (c *Context) GetHeader(key string) string
- func (c *Context) GetInt(key string) (i int)
- func (c *Context) GetInt64(key string) (i64 int64)
- func (c *Context) GetString(key string) (s string)
- func (c *Context) GetStringMap(key string) (sm map[string]interface{})
- func (c *Context) GetStringMapString(key string) (sms map[string]string)
- func (c *Context) GetStringMapStringSlice(key string) (smss map[string][]string)
- func (c *Context) GetStringSlice(key string) (ss []string)
- func (c *Context) GetTime(key string) (t time.Time)
- func (c *Context) GetUint(key string) (ui uint)
- func (c *Context) GetUint64(key string) (ui64 uint64)
- func (c *Context) Handler() HandlerFunc
- func (c *Context) HandlerName() string
- func (c *Context) HandlerNames() []string
- func (c *Context) Header(key, value string)
- func (c *Context) IsAborted() bool
- func (c *Context) JSON(code int, obj interface{})
- func (c *Context) Next()
- func (c *Context) Param(key string) string
- func (c *Context) RemoteIP() string
- func (c *Context) Render(code int, r Render)
- func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error
- func (c *Context) Set(key string, value interface{})
- func (c *Context) SetAccepted(formats ...string)
- func (c *Context) SetSameSite(samesite http.SameSite)
- func (c *Context) ShouldBindUri(obj interface{}) error
- func (c *Context) String(code int, format string, values ...interface{})
- func (c *Context) WriteHeader(code int)
- func (c *Context) XML(code int, obj interface{})
- type DataRender
- type Engine
- func (engine *Engine) Delims(left, right string) *Engine
- func (engine *Engine) HandleContext(c *Context)
- func (engine *Engine) HandleRequest(r IRequest, resp ResponseWriter) (err error)
- func (engine *Engine) LoadHTMLFiles(files ...string)
- func (engine *Engine) LoadHTMLGlob(pattern string)
- func (engine *Engine) NoMethod(handlers ...HandlerFunc)
- func (engine *Engine) NoRoute(handlers ...HandlerFunc)
- func (engine *Engine) Routes() (routes RoutesInfo)
- func (engine *Engine) SecureJsonPrefix(prefix string) *Engine
- func (engine *Engine) SetFuncMap(funcMap template.FuncMap)
- func (engine *Engine) SetHTMLTemplate(templ *template.Template)
- func (engine *Engine) SetTrustedProxies(trustedProxies []string) error
- func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes
- type Error
- type ErrorType
- type H
- type HandlerFunc
- type HandlersChain
- type IRequest
- type IRouter
- type IRoutes
- type JSONRender
- type Param
- type Params
- type Render
- type ResponseWriter
- type RouteInfo
- type RouterGroup
- func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes
- func (group *RouterGroup) BasePath() string
- func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes
- func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup
- func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes
- func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoutes
- func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes
- type RoutesInfo
- type StringRender
- type XMLRender
Constants ¶
const ( MIMEJSON = binding.MIMEJSON MIMEHTML = binding.MIMEHTML MIMEXML = binding.MIMEXML MIMEXML2 = binding.MIMEXML2 MIMEPlain = binding.MIMEPlain MIMEPOSTForm = binding.MIMEPOSTForm MIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm MIMEYAML = binding.MIMEYAML )
Content-Type MIME of the most common data formats.
const ( // When running on Google App Engine. Trust X-Appengine-Remote-Addr // for determining the client's IP PlatformGoogleAppEngine = "X-Appengine-Remote-Addr" // When using Cloudflare's CDN. Trust CF-Connecting-IP for determining // the client's IP PlatformCloudflare = "CF-Connecting-IP" )
Trusted platforms
const ( // DebugMode indicates gin mode is debug. DebugMode = "debug" // ReleaseMode indicates gin mode is release. ReleaseMode = "release" // TestMode indicates gin mode is test. TestMode = "test" )
const BodyBytesKey = "_gin-gonic/gin/bodybyteskey"
BodyBytesKey indicates a default body bytes key.
const EnvGinMode = "GIN_MODE"
EnvGinMode indicates environment name for gin mode.
Variables ¶
var DebugPrintRouteFunc func(httpMethod, absolutePath, handlerName string, nuHandlers int)
DebugPrintRouteFunc indicates debug log output format.
var DefaultErrorWriter io.Writer = os.Stderr
DefaultErrorWriter is the default io.Writer used by Gin to debug errors
var DefaultWriter io.Writer = os.Stdout
DefaultWriter is the default io.Writer used by Gin for debug output and middleware output like Logger() or Recovery(). Note that both Logger and Recovery provides custom ways to configure their output io.Writer. To support coloring in Windows use:
import "github.com/mattn/go-colorable" gin.DefaultWriter = colorable.NewColorableStdout()
Functions ¶
func DisableBindValidation ¶
func DisableBindValidation()
DisableBindValidation closes the default validator.
func EnableJsonDecoderDisallowUnknownFields ¶
func EnableJsonDecoderDisallowUnknownFields()
EnableJsonDecoderDisallowUnknownFields sets true for binding.EnableDecoderDisallowUnknownFields to call the DisallowUnknownFields method on the JSON Decoder instance.
func EnableJsonDecoderUseNumber ¶
func EnableJsonDecoderUseNumber()
EnableJsonDecoderUseNumber sets true for binding.EnableDecoderUseNumber to call the UseNumber method on the JSON Decoder instance.
func IsDebugging ¶
func IsDebugging() bool
IsDebugging returns true if the framework is running in debug mode. Use SetMode(gin.ReleaseMode) to disable debug mode.
func WriteJSON ¶
func WriteJSON(w ResponseWriter, obj interface{}) error
WriteJSON marshals the given interface object and writes it with custom ContentType.
Types ¶
type Context ¶
type Context struct { Request IRequest Writer ResponseWriter Params Params // Keys is a key/value pair exclusively for the context of each request. Keys map[string]interface{} // Errors is a list of errors attached to all the handlers/middlewares who used this context. Errors errorMsgs // Accepted defines a list of manually accepted formats for content negotiation. Accepted []string // contains filtered or unexported fields }
Context is the most important part of gin. It allows us to pass variables between middleware, manage the flow, validate the JSON of a request and render a JSON response for example.
func (*Context) Abort ¶
func (c *Context) Abort()
Abort prevents pending handlers from being called. Note that this will not stop the current handler. Let's say you have an authorization middleware that validates that the current request is authorized. If the authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers for this request are not called.
func (*Context) AbortWithError ¶
AbortWithError calls `AbortWithStatus()` and `Error()` internally. This method stops the chain, writes the status code and pushes the specified error to `c.Errors`. See Context.Error() for more details.
func (*Context) AbortWithStatus ¶
AbortWithStatus calls `Abort()` and writes the headers with the specified status code. For example, a failed attempt to authenticate a request could use: context.AbortWithStatus(401).
func (*Context) AbortWithStatusJSON ¶
AbortWithStatusJSON calls `Abort()` and then `JSON` internally. This method stops the chain, writes the status code and return a JSON body. It also sets the Content-Type as "application/json".
func (*Context) AddParam ¶
AddParam adds param to context and replaces path param key with given value for e2e testing purposes Example Route: "/user/:id" AddParam("id", 1) Result: "/user/1"
func (*Context) BindUri ¶
BindUri binds the passed struct pointer using binding.Uri. It will abort the request with HTTP 400 if any error occurs.
func (*Context) ClientIP ¶
ClientIP implements one best effort algorithm to return the real client IP. It called c.RemoteIP() under the hood, to check if the remote IP is a trusted proxy or not. If it is it will then try to parse the headers defined in Engine.RemoteIPHeaders (defaulting to [X-Forwarded-For, X-Real-Ip]). If the headers are not syntactically valid OR the remote IP does not correspond to a trusted proxy, the remote IP (coming from Request.RemoteAddr) is returned.
func (*Context) ContentType ¶
ContentType returns the Content-Type header of the request.
func (*Context) Copy ¶
Copy returns a copy of the current context that can be safely used outside the request's scope. This has to be used when the context has to be passed to a goroutine.
func (*Context) Error ¶
Error attaches an error to the current context. The error is pushed to a list of errors. It's a good idea to call Error for each error that occurred during the resolution of a request. A middleware can be used to collect all the errors and push them to a database together, print a log, or append it in the HTTP response. Error will panic if err is nil.
func (*Context) FullPath ¶
FullPath returns a matched route full path. For not found routes returns an empty string.
router.GET("/user/:id", func(c *gin.Context) { c.FullPath() == "/user/:id" // true })
func (*Context) Get ¶
Get returns the value for the given key, ie: (value, true). If the value does not exist it returns (nil, false)
func (*Context) GetDuration ¶
GetDuration returns the value associated with the key as a duration.
func (*Context) GetFloat64 ¶
GetFloat64 returns the value associated with the key as a float64.
func (*Context) GetStringMap ¶
GetStringMap returns the value associated with the key as a map of interfaces.
func (*Context) GetStringMapString ¶
GetStringMapString returns the value associated with the key as a map of strings.
func (*Context) GetStringMapStringSlice ¶
GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.
func (*Context) GetStringSlice ¶
GetStringSlice returns the value associated with the key as a slice of strings.
func (*Context) GetUint64 ¶
GetUint64 returns the value associated with the key as an unsigned integer.
func (*Context) HandlerName ¶
HandlerName returns the main handler's name. For example if the handler is "handleGetUsers()", this function will return "main.handleGetUsers".
func (*Context) HandlerNames ¶
HandlerNames returns a list of all registered handlers for this context in descending order, following the semantics of HandlerName()
func (*Context) Header ¶
Header is an intelligent shortcut for c.Writer.Header().Set(key, value). It writes a header in the response. If value == "", this method removes the header `c.Writer.Header().Del(key)`
func (*Context) JSON ¶
JSON serializes the given struct as JSON into the response body. It also sets the Content-Type as "application/json".
func (*Context) Next ¶
func (c *Context) Next()
Next should be used only inside middleware. It executes the pending handlers in the chain inside the calling handler. See example in GitHub.
func (*Context) Param ¶
Param returns the value of the URL param. It is a shortcut for c.Params.ByName(key)
router.GET("/user/:id", func(c *gin.Context) { // a GET request to /user/john id := c.Param("id") // id == "john" })
func (*Context) RemoteIP ¶
RemoteIP parses the IP from Request.RemoteAddr, normalizes and returns the IP (without the port).
func (*Context) SaveUploadedFile ¶
func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error
SaveUploadedFile uploads the form file to specific dst.
func (*Context) Set ¶
Set is used to store a new key/value pair exclusively for this context. It also lazy initializes c.Keys if it was not used previously.
func (*Context) SetAccepted ¶
SetAccepted sets Accept header data.
func (*Context) SetSameSite ¶
SetSameSite with cookie
func (*Context) ShouldBindUri ¶
ShouldBindUri binds the passed struct pointer using the specified binding engine.
func (*Context) WriteHeader ¶
Status sets the HTTP response code.
type DataRender ¶
Data contains ContentType and bytes data.
func (DataRender) Render ¶
func (r DataRender) Render(w ResponseWriter) (err error)
Render (Data) writes data with custom ContentType.
func (DataRender) WriteContentType ¶
func (r DataRender) WriteContentType(w ResponseWriter)
WriteContentType (Data) writes custom ContentType.
type Engine ¶
type Engine struct { RouterGroup // Enables automatic redirection if the current route can't be matched but a // handler for the path with (without) the trailing slash exists. // For example if /foo/ is requested but a route only exists for /foo, the // client is redirected to /foo with http status code 301 for GET requests // and 307 for all other request methods. RedirectTrailingSlash bool // If enabled, the router tries to fix the current request path, if no // handle is registered for it. // First superfluous path elements like ../ or // are removed. // Afterwards the router does a case-insensitive lookup of the cleaned path. // If a handle can be found for this route, the router makes a redirection // to the corrected path with status code 301 for GET requests and 307 for // all other request methods. // For example /FOO and /..//Foo could be redirected to /foo. // RedirectTrailingSlash is independent of this option. RedirectFixedPath bool // If enabled, the router checks if another method is allowed for the // current route, if the current request can not be routed. // If this is the case, the request is answered with 'Method Not Allowed' // and HTTP status code 405. // If no other Method is allowed, the request is delegated to the NotFound // handler. HandleMethodNotAllowed bool // If enabled, client IP will be parsed from the request's headers that // match those stored at `(*gin.Engine).RemoteIPHeaders`. If no IP was // fetched, it falls back to the IP obtained from // `(*gin.Context).Request.RemoteAddr`. ForwardedByClientIP bool // DEPRECATED: USE `TrustedPlatform` WITH VALUE `gin.PlatformGoogleAppEngine` INSTEAD // #726 #755 If enabled, it will trust some headers starting with // 'X-AppEngine...' for better integration with that PaaS. AppEngine bool // If enabled, the url.RawPath will be used to find parameters. UseRawPath bool // If true, the path value will be unescaped. // If UseRawPath is false (by default), the UnescapePathValues effectively is true, // as url.Path gonna be used, which is already unescaped. UnescapePathValues bool // RemoveExtraSlash a parameter can be parsed from the URL even with extra slashes. // See the PR #1817 and issue #1644 RemoveExtraSlash bool // List of headers used to obtain the client IP when // `(*gin.Engine).ForwardedByClientIP` is `true` and // `(*gin.Context).Request.RemoteAddr` is matched by at least one of the // network origins of list defined by `(*gin.Engine).SetTrustedProxies()`. RemoteIPHeaders []string // If set to a constant of value gin.Platform*, trusts the headers set by // that platform, for example to determine the client IP TrustedPlatform string // Value of 'maxMemory' param that is given to http.Request's ParseMultipartForm // method call. MaxMultipartMemory int64 // Enable h2c support. UseH2C bool HTMLRender render.HTMLRender FuncMap template.FuncMap // contains filtered or unexported fields }
Engine is the framework's instance, it contains the muxer, middleware and configuration settings. Create an instance of Engine, by using New() or Default()
func Default ¶
func Default() *Engine
Default returns an Engine instance with the Logger and Recovery middleware already attached.
func New ¶
func New() *Engine
New returns a new blank Engine instance without any middleware attached. By default, the configuration is: - RedirectTrailingSlash: true - RedirectFixedPath: false - HandleMethodNotAllowed: false - ForwardedByClientIP: true - UseRawPath: false - UnescapePathValues: true
func (*Engine) HandleContext ¶
HandleContext re-enters a context that has been rewritten. This can be done by setting c.Request.URL.Path to your new target. Disclaimer: You can loop yourself to deal with this, use wisely.
func (*Engine) HandleRequest ¶
func (engine *Engine) HandleRequest(r IRequest, resp ResponseWriter) (err error)
HandleRequest 处理外部请求
func (*Engine) LoadHTMLFiles ¶
LoadHTMLFiles loads a slice of HTML files and associates the result with HTML renderer.
func (*Engine) LoadHTMLGlob ¶
LoadHTMLGlob loads HTML files identified by glob pattern and associates the result with HTML renderer.
func (*Engine) NoMethod ¶
func (engine *Engine) NoMethod(handlers ...HandlerFunc)
NoMethod sets the handlers called when Engine.HandleMethodNotAllowed = true.
func (*Engine) NoRoute ¶
func (engine *Engine) NoRoute(handlers ...HandlerFunc)
NoRoute adds handlers for NoRoute. It returns a 404 code by default.
func (*Engine) Routes ¶
func (engine *Engine) Routes() (routes RoutesInfo)
Routes returns a slice of registered routes, including some useful information, such as: the http method, path and the handler name.
func (*Engine) SecureJsonPrefix ¶
SecureJsonPrefix sets the secureJSONPrefix used in Context.SecureJSON.
func (*Engine) SetFuncMap ¶
SetFuncMap sets the FuncMap used for template.FuncMap.
func (*Engine) SetHTMLTemplate ¶
SetHTMLTemplate associate a template with HTML renderer.
func (*Engine) SetTrustedProxies ¶
SetTrustedProxies set a list of network origins (IPv4 addresses, IPv4 CIDRs, IPv6 addresses or IPv6 CIDRs) from which to trust request's headers that contain alternative client IP when `(*gin.Engine).ForwardedByClientIP` is `true`. `TrustedProxies` feature is enabled by default, and it also trusts all proxies by default. If you want to disable this feature, use Engine.SetTrustedProxies(nil), then Context.ClientIP() will return the remote address directly.
func (*Engine) Use ¶
func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes
Use attaches a global middleware to the router. i.e. the middleware attached through Use() will be included in the handlers chain for every single request. Even 404, 405, static files... For example, this is the right place for a logger or error management middleware.
type Error ¶
Error represents a error's specification.
func (*Error) MarshalJSON ¶
MarshalJSON implements the json.Marshaller interface.
type ErrorType ¶
type ErrorType uint64
ErrorType is an unsigned 64-bit error code as defined in the gin spec.
const ( // ErrorTypeBind is used when Context.Bind() fails. ErrorTypeBind ErrorType = 1 << 63 // ErrorTypeRender is used when Context.Render() fails. ErrorTypeRender ErrorType = 1 << 62 // ErrorTypePrivate indicates a private error. ErrorTypePrivate ErrorType = 1 << 0 // ErrorTypePublic indicates a public error. ErrorTypePublic ErrorType = 1 << 1 // ErrorTypeAny indicates any other error. ErrorTypeAny ErrorType = 1<<64 - 1 // ErrorTypeNu indicates any other error. ErrorTypeNu = 2 )
type H ¶
type H map[string]interface{}
H is a shortcut for map[string]interface{}
func (H) MarshalXML ¶
MarshalXML allows type H to be used with xml.Marshal.
type HandlerFunc ¶
type HandlerFunc func(*Context)
HandlerFunc defines the handler used by gin middleware as return value.
type HandlersChain ¶
type HandlersChain []HandlerFunc
HandlersChain defines a HandlerFunc slice.
func (HandlersChain) Last ¶
func (c HandlersChain) Last() HandlerFunc
Last returns the last handler in the chain. i.e. the last handler is the main one.
type IRouter ¶
type IRouter interface { IRoutes Group(string, ...HandlerFunc) *RouterGroup }
IRouter defines all router handle interface includes single and group router.
type IRoutes ¶
type IRoutes interface { Use(...HandlerFunc) IRoutes Handle(string, string, ...HandlerFunc) IRoutes Any(string, ...HandlerFunc) IRoutes GET(string, ...HandlerFunc) IRoutes POST(string, ...HandlerFunc) IRoutes }
IRoutes defines all router handle interface.
type JSONRender ¶
type JSONRender struct {
Data interface{}
}
JSON contains the given interface object.
func (JSONRender) Render ¶
func (r JSONRender) Render(w ResponseWriter) (err error)
Render (JSON) writes data with custom ContentType.
func (JSONRender) WriteContentType ¶
func (r JSONRender) WriteContentType(w ResponseWriter)
WriteContentType (JSON) writes JSON ContentType.
type Params ¶
type Params []Param
Params is a Param-slice, as returned by the router. The slice is ordered, the first URL parameter is also the first slice value. It is therefore safe to read values by the index.
type Render ¶
type Render interface { // Render writes data with custom ContentType. Render(ResponseWriter) error // WriteContentType writes custom ContentType. WriteContentType(w ResponseWriter) }
Render interface is to be implemented by JSON, XML, HTML, YAML and so on.
type ResponseWriter ¶
type ResponseWriter interface { // Returns the HTTP response status code of the current request. Status() int // Returns the number of bytes already written into the response http body. // See Written() Size() int // Returns true if the response body was already written. Written() bool WriteHeader(code int) Header() xtypes.SMap Write(p []byte) (n int, err error) // Writes the string into the response body. WriteString(string) (int, error) Flush() error }
ResponseWriter ...
type RouteInfo ¶
type RouteInfo struct { Method string Path string Handler string HandlerFunc HandlerFunc }
RouteInfo represents a request route's specification which contains method and path and its handler.
type RouterGroup ¶
type RouterGroup struct { Handlers HandlersChain // contains filtered or unexported fields }
RouterGroup is used internally to configure router, a RouterGroup is associated with a prefix and an array of handlers (middleware).
func (*RouterGroup) Any ¶
func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes
Any registers a route that matches all the HTTP methods. GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE.
func (*RouterGroup) BasePath ¶
func (group *RouterGroup) BasePath() string
BasePath returns the base path of router group. For example, if v := router.Group("/rest/n/v1/api"), v.BasePath() is "/rest/n/v1/api".
func (*RouterGroup) GET ¶
func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes
GET is a shortcut for router.Handle("GET", path, handle).
func (*RouterGroup) Group ¶
func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup
Group creates a new router group. You should add all the routes that have common middlewares or the same path prefix. For example, all the routes that use a common middleware for authorization could be grouped.
func (*RouterGroup) Handle ¶
func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes
Handle registers a new request handle and middleware with the given path and method. The last handler should be the real handler, the other ones should be middleware that can and should be shared among different routes. See the example code in GitHub.
For GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used.
This function is intended for bulk loading and to allow the usage of less frequently used, non-standardized or custom methods (e.g. for internal communication with a proxy).
func (*RouterGroup) POST ¶
func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoutes
POST is a shortcut for router.Handle("POST", path, handle).
func (*RouterGroup) Use ¶
func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes
Use adds middleware to the group, see example code in GitHub.
type StringRender ¶
type StringRender struct { Format string Data []interface{} }
String contains the given interface object slice and its format.
func (StringRender) Render ¶
func (r StringRender) Render(w ResponseWriter) error
Render (String) writes data with custom ContentType.
func (StringRender) WriteContentType ¶
func (r StringRender) WriteContentType(w ResponseWriter)
WriteContentType (String) writes Plain ContentType.
type XMLRender ¶
type XMLRender struct {
Data interface{}
}
XML contains the given interface object.
func (XMLRender) Render ¶
func (r XMLRender) Render(w ResponseWriter) error
Render (XML) encodes the given interface object and writes data with custom ContentType.
func (XMLRender) WriteContentType ¶
func (r XMLRender) WriteContentType(w ResponseWriter)
WriteContentType (XML) writes XML ContentType for response.