Documentation
¶
Index ¶
- Constants
- type Context
- func (ctx *Context) Abort()
- func (ctx *Context) AbortWithError(code int, format string, values ...interface{})
- func (ctx *Context) AbortWithStatus(code int)
- func (ctx *Context) Attachment(content io.Reader, filename string) (err error)
- func (ctx *Context) AttachmentFile(filepath, filename string) (err error)
- func (ctx *Context) BindJSON(obj interface{}) (err error)
- func (ctx *Context) BindWith(obj interface{}, b binder.Binder) (err error)
- func (ctx *Context) BindXML(obj interface{}) (err error)
- func (ctx *Context) ClientIP() (ip string)
- func (ctx *Context) Cookie(name string) (*http.Cookie, error)
- func (ctx *Context) Copy() *Context
- func (ctx *Context) DefaultFormValue(name, defaultValue string) string
- func (ctx *Context) DefaultPostFormValue(name, defaultValue string) (value string)
- func (ctx *Context) DefaultQuery(name, defaultValue string) string
- func (ctx *Context) Delete(key string)
- func (ctx *Context) FormValue(name string) string
- func (ctx *Context) Get(key string) (value interface{}, exists bool)
- func (ctx *Context) HandlerName() string
- func (ctx *Context) IsAborted() bool
- func (ctx *Context) JSON(code int, obj interface{}) (err error)
- func (ctx *Context) JSONBlob(code int, blob []byte) (err error)
- func (ctx *Context) JSONIndent(code int, obj interface{}, prefix string, indent string) (err error)
- func (ctx *Context) MustGet(key string) interface{}
- func (ctx *Context) Next()
- func (ctx *Context) NoContent(code int) error
- func (ctx *Context) Param(name string) string
- func (ctx *Context) ParamByIndex(index int) string
- func (ctx *Context) PostFormValue(name string) (value string)
- func (ctx *Context) Query(name string) string
- func (ctx *Context) QueryParams() url.Values
- func (ctx *Context) Redirect(code int, location string)
- func (ctx *Context) ServeContent(content io.ReadSeeker, name string, modtime time.Time) (err error)
- func (ctx *Context) ServeFile(filepath string) (err error)
- func (ctx *Context) Set(key string, value interface{})
- func (ctx *Context) SetCookie(cookie *http.Cookie)
- func (ctx *Context) String(code int, format string, values ...interface{}) (err error)
- func (ctx *Context) XML(code int, obj interface{}) (err error)
- func (ctx *Context) XMLBlob(code int, blob []byte) (err error)
- func (ctx *Context) XMLIndent(code int, obj interface{}, prefix string, indent string) (err error)
- type Dir
- type Engine
- func (engine *Engine) DebugPProf(middleware ...HandlerFunc)
- func (engine *Engine) DefaultValidator(v StructValidator)
- func (engine *Engine) FetchClientIPFromHeader(b bool)
- func (engine *Engine) HandleMethodNotAllowed(b bool)
- func (engine *Engine) NoMethod(handlers ...HandlerFunc)
- func (engine *Engine) NoRoute(handlers ...HandlerFunc)
- func (engine *Engine) RedirectFixedPath(b bool)
- func (engine *Engine) RedirectTrailingSlash(b bool)
- func (engine *Engine) Routes() []Route
- func (engine *Engine) Run(addr string) (err error)
- func (engine *Engine) RunTLS(addr string, certFile string, keyFile string) (err error)
- func (engine *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (engine *Engine) Use(middleware ...HandlerFunc)
- type H
- type HandlerChain
- type HandlerFunc
- type Param
- type Params
- type ResponseWriter
- type Route
- type RouteGroup
- func (group *RouteGroup) Any(relativePath string, handlers ...HandlerFunc)
- func (group *RouteGroup) BasePath() string
- func (group *RouteGroup) Connect(relativePath string, handlers ...HandlerFunc)
- func (group *RouteGroup) Delete(relativePath string, handlers ...HandlerFunc)
- func (group *RouteGroup) Get(relativePath string, handlers ...HandlerFunc)
- func (group *RouteGroup) Group(relativePath string, middlewares ...HandlerFunc) *RouteGroup
- func (group *RouteGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc)
- func (group *RouteGroup) Head(relativePath string, handlers ...HandlerFunc)
- func (group *RouteGroup) Options(relativePath string, handlers ...HandlerFunc)
- func (group *RouteGroup) Patch(relativePath string, handlers ...HandlerFunc)
- func (group *RouteGroup) Post(relativePath string, handlers ...HandlerFunc)
- func (group *RouteGroup) Put(relativePath string, handlers ...HandlerFunc)
- func (group *RouteGroup) StaticAlias(relativePath string, dir http.FileSystem)
- func (group *RouteGroup) StaticFile(relativePath, filepath string)
- func (group *RouteGroup) StaticRoot(relativePath string, root http.FileSystem)
- func (group *RouteGroup) Trace(relativePath string, handlers ...HandlerFunc)
- func (group *RouteGroup) Use(middlewares ...HandlerFunc)
- type StructValidator
Constants ¶
const ( HTTPMethodGet = http.MethodGet HTTPMethodHead = http.MethodHead HTTPMethodPost = http.MethodPost HTTPMethodPut = http.MethodPut HTTPMethodPatch = http.MethodPatch HTTPMethodDelete = http.MethodDelete HTTPMethodConnect = http.MethodConnect HTTPMethodOptions = http.MethodOptions HTTPMethodTrace = http.MethodTrace )
Common HTTP methods.
Unless otherwise noted, these are defined in RFC 7231 section 4.3.
const ( MIMEApplicationURLEncodedForm = "application/x-www-form-urlencoded" MIMEMultipartForm = "multipart/form-data" MIMEApplicationOctetStream = "application/octet-stream" MIMEApplicationProtobuf = "application/protobuf" MIMEApplicationJSON = "application/json" MIMEApplicationXML = "application/xml" MIMEApplicationJavaScript = "application/javascript" MIMETextPlain = "text/plain" MIMETextHTML = "text/html" MIMETextXML = "text/xml" MIMEApplicationJSONCharsetUTF8 = MIMEApplicationJSON + "; charset=utf-8" MIMEApplicationXMLCharsetUTF8 = MIMEApplicationXML + "; charset=utf-8" MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; charset=utf-8" MIMETextPlainCharsetUTF8 = MIMETextPlain + "; charset=utf-8" MIMETextHTMLCharsetUTF8 = MIMETextHTML + "; charset=utf-8" MIMETextXMLCharsetUTF8 = MIMETextXML + "; charset=utf-8" )
MIME types
const ( HeaderAcceptEncoding = "Accept-Encoding" HeaderAuthorization = "Authorization" HeaderContentDisposition = "Content-Disposition" HeaderContentEncoding = "Content-Encoding" HeaderContentLength = "Content-Length" HeaderContentType = "Content-Type" HeaderCookie = "Cookie" HeaderSetCookie = "Set-Cookie" HeaderIfModifiedSince = "If-Modified-Since" HeaderLastModified = "Last-Modified" HeaderLocation = "Location" HeaderUpgrade = "Upgrade" HeaderVary = "Vary" HeaderWWWAuthenticate = "WWW-Authenticate" HeaderXForwardedProto = "X-Forwarded-Proto" HeaderXHTTPMethodOverride = "X-HTTP-Method-Override" HeaderXForwardedFor = "X-Forwarded-For" HeaderXRealIP = "X-Real-IP" HeaderServer = "Server" HeaderOrigin = "Origin" HeaderAccessControlRequestMethod = "Access-Control-Request-Method" HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers" HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin" HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods" HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers" HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials" HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers" HeaderAccessControlMaxAge = "Access-Control-Max-Age" // Security HeaderStrictTransportSecurity = "Strict-Transport-Security" HeaderXContentTypeOptions = "X-Content-Type-Options" HeaderXXSSProtection = "X-XSS-Protection" HeaderXFrameOptions = "X-Frame-Options" HeaderContentSecurityPolicy = "Content-Security-Policy" HeaderXCSRFToken = "X-CSRF-Token" )
Headers
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Context ¶
type Context struct { ResponseWriter ResponseWriter // convert from Context.responseWriter2 Request *http.Request PathParams Params // Validator will validate object when binding if not nil. // By default the Validator is nil, you can set default Validator using // Engine.DefaultValidator() // also you can change this in handlers. Validator StructValidator // 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.
NOTE: Context and the ResponseWriter, PathParams fields of Context can NOT be safely used outside the request's scope, see Context.Copy().
func (*Context) Abort ¶
func (ctx *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 writes the status code and error message to response, then stops the chain. The error message should be plain text. This method calls `String()` internally, see Context.String() for more details.
func (*Context) AbortWithStatus ¶
AbortWithStatus writes the headers with the specified status code and calls `Abort()`. For example, a failed attempt to authentificate a request could use: context.AbortWithStatus(401).
func (*Context) Attachment ¶
Attachment adds a `Content-Disposition:attachment;filename="XXX"` header and writes the specified content into the body stream.
func (*Context) AttachmentFile ¶
AttachmentFile adds a `Content-Disposition:attachment;filename="XXX"` header and writes the specified file into the body stream.
filename can be empty, in that case name of the file is used.
func (*Context) Cookie ¶
Cookie is a shortcut for ctx.Request.Cookie(name). It returns the named cookie provided in the request or http.ErrNoCookie if not found.
func (*Context) Copy ¶
Copy returns a copy of the current context that can be safely used outside the request's scope. This have to be used when the context has to be passed to a goroutine.
func (*Context) DefaultFormValue ¶
DefaultFormValue like FormValue if name matched, otherwise it returns defaultValue.
func (*Context) DefaultPostFormValue ¶
DefaultPostFormValue like PostFormValue if name matched, otherwise it returns defaultValue.
func (*Context) DefaultQuery ¶
DefaultQuery like Query if name matched, otherwise it returns defaultValue.
func (*Context) Get ¶
Get returns the value for the given key, ie: (value, true). If the value does not exists it returns (nil, false)
func (*Context) HandlerName ¶
HandlerName returns the main handle's name. For example if the handler is "handleGetUsers()", this function will return "main.handleGetUsers"
func (*Context) JSON ¶
JSON sends a JSON response with status code. It sets the Content-Type as "application/json; charset=utf-8".
func (*Context) JSONBlob ¶
JSONBlob sends a JSON response with status code. It sets the Content-Type as "application/json; charset=utf-8".
func (*Context) JSONIndent ¶
JSONIndent sends a JSON response with status code, but it applies prefix and indent to format the output. It sets the Content-Type as "application/json; charset=utf-8".
func (*Context) MustGet ¶
MustGet returns the value for the given key if it exists, otherwise it panics.
func (*Context) Next ¶
func (ctx *Context) Next()
Next should be used only inside middleware. It executes the pending handlers in the chain inside the calling handler.
func (*Context) ParamByIndex ¶
ParamByIndex is a shortcut for ctx.PathParams.ByIndex(index).
func (*Context) PostFormValue ¶
PostFormValue is a shortcut for ctx.Request.PostFormValue(name).
func (*Context) QueryParams ¶
QueryParams returns the url query values.
func (*Context) ServeContent ¶
ServeContent is wrapper for http.ServeContent.
func (*Context) String ¶
String writes the given string into the response body. It sets the Content-Type as "text/plain; charset=utf-8".
func (*Context) XML ¶
XML sends an XML response with status code. It sets the Content-Type as "application/xml; charset=utf-8".
type Dir ¶
type Dir string
Dir like http.Dir but the http.File returned by Dir.Open() does not list the directory files, so we can pass Dir to http.FileServer() to prevent it lists the directory files.
type Engine ¶
type Engine struct { RouteGroup // 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().
NOTE: Engine is NOT copyable. Please serially sets Engine(normally in 'init' or 'main' goroutine).
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
func (*Engine) DebugPProf ¶
func (engine *Engine) DebugPProf(middleware ...HandlerFunc)
DebugPProf registers internal HandlerFunc to process path "/debug/pprof/*name", for more information please see net/http/pprof.
Please NOTE that DebugPProf does not use any middleware of Engine, you can specify middlewares optionally when you call this method.
func (*Engine) DefaultValidator ¶
func (engine *Engine) DefaultValidator(v StructValidator)
DefaultValidator sets the default Validator to validate object when binding.
func (*Engine) FetchClientIPFromHeader ¶
If enabled, the engine get client IP from http hearder X-Real-IP, X-Forwarded-For.
Default is false.
func (*Engine) HandleMethodNotAllowed ¶
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.
Default is false.
func (*Engine) NoMethod ¶
func (engine *Engine) NoMethod(handlers ...HandlerFunc)
NoMethod set handlers for NoMethod. It return a 405 code by default. Engine.NoMethod() removes all no-method handlers.
func (*Engine) NoRoute ¶
func (engine *Engine) NoRoute(handlers ...HandlerFunc)
NoRoute set handlers for NoRoute. It return a 404 code by default. Engine.NoRoute() removes all no-route handlers.
func (*Engine) RedirectFixedPath ¶
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.
Default is false.
func (*Engine) RedirectTrailingSlash ¶
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.
Default is true.
func (*Engine) Routes ¶
Routes returns a slice of registered routes, including some useful information, such as: the http method, path and the handler name.
func (*Engine) Run ¶
Run attaches the engine to a http.Server and starts listening and serving HTTP requests. It is a shortcut for http.ListenAndServe(addr, engine) Note: this method will block the calling goroutine indefinitely unless an error happens.
func (*Engine) RunTLS ¶
RunTLS attaches the engine to a http.Server and starts listening and serving HTTPS (secure) requests. It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, engine) Note: this method will block the calling goroutine indefinitely unless an error happens.
func (*Engine) ServeHTTP ¶
func (engine *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements the http.Handler interface.
func (*Engine) Use ¶
func (engine *Engine) Use(middleware ...HandlerFunc)
Attachs a global middleware to Engine. ie. the middleware attached though Use() will be included in the handler 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 HandlerChain ¶
type HandlerChain []HandlerFunc
type HandlerFunc ¶
type HandlerFunc func(*Context)
func WrapHandler ¶
func WrapHandler(h http.Handler) HandlerFunc
func WrapHandlerFunc ¶
func WrapHandlerFunc(fn http.HandlerFunc) HandlerFunc
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 ResponseWriter ¶
type ResponseWriter response.ResponseWriter
type ResponseWriter interface { http.ResponseWriter WroteHeader() bool // WroteHeader returns true if header has been written, otherwise false. Status() int // Status returns the response status code of the current request. Written() int64 // Written returns number of bytes written in body. }
type RouteGroup ¶
type RouteGroup struct {
// contains filtered or unexported fields
}
RouteGroup is used to configure the internal router, a RouteGroup is associated with a path prefix and an array of middlewares.
NOTE: Please serially sets RouteGroup(normally in 'init' or 'main' goroutine).
func (*RouteGroup) Any ¶
func (group *RouteGroup) Any(relativePath string, handlers ...HandlerFunc)
Any registers a route that matches all the HTTP methods: GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE.
func (*RouteGroup) BasePath ¶
func (group *RouteGroup) BasePath() string
BasePath returns the path prefix of this RouteGroup.
func (*RouteGroup) Connect ¶
func (group *RouteGroup) Connect(relativePath string, handlers ...HandlerFunc)
Connect is a shortcut for group.Handle("CONNECT", relativePath, handlers)
func (*RouteGroup) Delete ¶
func (group *RouteGroup) Delete(relativePath string, handlers ...HandlerFunc)
Delete is a shortcut for group.Handle("DELETE", relativePath, handlers)
func (*RouteGroup) Get ¶
func (group *RouteGroup) Get(relativePath string, handlers ...HandlerFunc)
Get is a shortcut for group.Handle("GET", relativePath, handlers)
func (*RouteGroup) Group ¶
func (group *RouteGroup) Group(relativePath string, middlewares ...HandlerFunc) *RouteGroup
Group creates a new RouteGroup. You should add all the routes that have common middlewares or the same path prefix. For example, all the routes that use a common middlware for authorization could be grouped.
func (*RouteGroup) Handle ¶
func (group *RouteGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc)
Handle registers a new request handler and middlewares 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, DELETE, HEAD, OPTIONS, CONNECT and TRACE 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 (*RouteGroup) Head ¶
func (group *RouteGroup) Head(relativePath string, handlers ...HandlerFunc)
Head is a shortcut for group.Handle("HEAD", relativePath, handlers)
func (*RouteGroup) Options ¶
func (group *RouteGroup) Options(relativePath string, handlers ...HandlerFunc)
Options is a shortcut for group.Handle("OPTIONS", relativePath, handlers)
func (*RouteGroup) Patch ¶
func (group *RouteGroup) Patch(relativePath string, handlers ...HandlerFunc)
Patch is a shortcut for group.Handle("PATCH", relativePath, handlers)
func (*RouteGroup) Post ¶
func (group *RouteGroup) Post(relativePath string, handlers ...HandlerFunc)
Post is a shortcut for group.Handle("POST", relativePath, handlers)
func (*RouteGroup) Put ¶
func (group *RouteGroup) Put(relativePath string, handlers ...HandlerFunc)
Put is a shortcut for group.Handle("PUT", relativePath, handlers)
func (*RouteGroup) StaticAlias ¶
func (group *RouteGroup) StaticAlias(relativePath string, dir http.FileSystem)
StaticAlias like nginx alias location(also relativePath must be ended with '/' if not empty).
group.StaticAlias("/abc/", http.Dir("/home/root/abc/")) group.StaticAlias("/abc/", gin.Dir("/home/root/abc/")) is like this in nginx: location ^~ /abc/ { alias /home/root/abc/; }
func (*RouteGroup) StaticFile ¶
func (group *RouteGroup) StaticFile(relativePath, filepath string)
StaticFile registers a single route in order to serve a single file of the local filesystem.
group.StaticFile("favicon.ico", "./resources/favicon.ico")
func (*RouteGroup) StaticRoot ¶
func (group *RouteGroup) StaticRoot(relativePath string, root http.FileSystem)
StaticRoot like nginx root location but relativePath must be ended with '/' if not empty.
group.StaticRoot("/abc/", http.Dir("/home/root")) group.StaticRoot("/abc/", gin.Dir("/home/root")) is like this in nginx: location ^~ /abc/ { root /home/root; }
func (*RouteGroup) Trace ¶
func (group *RouteGroup) Trace(relativePath string, handlers ...HandlerFunc)
Trace is a shortcut for group.Handle("TRACE", relativePath, handlers)
func (*RouteGroup) Use ¶
func (group *RouteGroup) Use(middlewares ...HandlerFunc)
Use adds middlewares to the group.
type StructValidator ¶
type StructValidator interface { // ValidateStruct can receive any kind of type and it should never panic, even if the obj is not right. // If the received type is not a struct, any validation should be skipped and nil must be returned. // If the received type is a struct or pointer to a struct, the validation should be performed. // If the struct is not valid or the validation itself fails, a descriptive error should be returned. // Otherwise nil must be returned. ValidateStruct(obj interface{}) error }
var DefaultValidator StructValidator = (*defaultValidator)(validator.New(&validator.Config{TagName: "validate"}))