Documentation ¶
Index ¶
- Constants
- Variables
- func CreateTestContext(w http.ResponseWriter) (c *Context, r *Engine)
- func Dir(root string, listDirectory bool) http.FileSystem
- func DisableBindValidation()
- func DisableConsoleColor()
- func EnableJsonDecoderDisallowUnknownFields()
- func EnableJsonDecoderUseNumber()
- func ForceConsoleColor()
- func IsDebugging() bool
- func Mode() string
- func SetMode(value string)
- type Accounts
- 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) AsciiJSON(code int, obj interface{})
- func (c *Context) BindWith(obj interface{}, b bind.IBind) error
- func (c *Context) CORS() HandlerFunc
- func (c *Context) ClientIP() string
- func (c *Context) ContentType() string
- func (c *Context) Cookie(name string) (string, error)
- func (c *Context) Copy() *Context
- func (c *Context) Data(code int, contentType string, data []byte)
- func (c *Context) DataFromReader(code int, contentLength int64, contentType string, reader io.Reader, ...)
- func (c *Context) Deadline() (deadline time.Time, ok bool)
- func (c *Context) DefaultPostForm(key, defaultValue string) string
- func (c *Context) DefaultQuery(key, defaultValue string) string
- func (c *Context) Done() <-chan struct{}
- func (c *Context) Err() error
- func (c *Context) Error(err error) *Error
- func (c *Context) File(filepath string)
- func (c *Context) FileAttachment(filepath, filename string)
- func (c *Context) FileFromFS(filepath string, fs http.FileSystem)
- func (c *Context) FormFile(name string) (*multipart.FileHeader, 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) GetPostForm(key string) (string, bool)
- func (c *Context) GetPostFormArray(key string) ([]string, bool)
- func (c *Context) GetPostFormMap(key string) (map[string]string, bool)
- func (c *Context) GetQuery(key string) (string, bool)
- func (c *Context) GetQueryArray(key string) ([]string, bool)
- func (c *Context) GetQueryMap(key string) (map[string]string, bool)
- func (c *Context) GetRawData() ([]byte, error)
- 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) HTML(code int, name string, obj interface{})
- 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) IndentedJSON(code int, obj interface{})
- func (c *Context) IsAborted() bool
- func (c *Context) IsWebsocket() bool
- func (c *Context) JSON(code int, obj interface{})
- func (c *Context) JSONP(code int, obj interface{})
- func (c *Context) MultipartForm() (*multipart.Form, error)
- func (c *Context) MustGet(key string) interface{}
- func (c *Context) Negotiate(code int, config Negotiate)
- func (c *Context) NegotiateFormat(offered ...string) string
- func (c *Context) Next()
- func (c *Context) Param(key string) string
- func (c *Context) Parse(obj interface{}) error
- func (c *Context) ParseBody(obj interface{}, bb bind.IBindBody) (err error)
- func (c *Context) ParseOnce(obj interface{}, b bind.IBind) error
- func (c *Context) ParseUri(obj interface{}) error
- func (c *Context) PostForm(key string) string
- func (c *Context) PostFormArray(key string) []string
- func (c *Context) PostFormMap(key string) map[string]string
- func (c *Context) ProtoBuf(code int, obj interface{})
- func (c *Context) PureJSON(code int, obj interface{})
- func (c *Context) Query(key string) string
- func (c *Context) QueryArray(key string) []string
- func (c *Context) QueryMap(key string) map[string]string
- func (c *Context) Redirect(code int, location string)
- func (c *Context) Render(code int, r render.IRender)
- func (c *Context) SSEvent(name string, message interface{})
- func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error
- func (c *Context) SecureJSON(code int, obj interface{})
- func (c *Context) Set(key string, value interface{})
- func (c *Context) SetAccepted(formats ...string)
- func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)
- func (c *Context) SetSameSite(samesite http.SameSite)
- func (c *Context) Status(code int)
- func (c *Context) Stream(step func(w io.Writer) bool) bool
- func (c *Context) String(code int, format string, values ...interface{})
- func (c *Context) Value(key interface{}) interface{}
- func (c *Context) XML(code int, obj interface{})
- func (c *Context) YAML(code int, obj interface{})
- type DiscardLogger
- func (DiscardLogger) Debug(v ...interface{})
- func (DiscardLogger) Debugf(format string, v ...interface{})
- func (DiscardLogger) Error(v ...interface{})
- func (DiscardLogger) Errorf(format string, v ...interface{})
- func (DiscardLogger) Info(v ...interface{})
- func (DiscardLogger) Infof(format string, v ...interface{})
- func (DiscardLogger) Level() LogLevel
- func (DiscardLogger) SetLevel(l LogLevel)
- func (DiscardLogger) Warn(v ...interface{})
- func (DiscardLogger) Warnf(format string, v ...interface{})
- type Engine
- func (engine *Engine) Delims(left, right string) *Engine
- func (engine *Engine) HandleContext(c *Context)
- 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) Run(addr ...string) (err error)
- func (engine *Engine) RunFd(fd int) (err error)
- func (engine *Engine) RunListener(listener net.Listener) (err error)
- func (engine *Engine) RunTLS(addr, certFile, keyFile string) (err error)
- func (engine *Engine) RunUnix(file string) (err error)
- func (engine *Engine) SecureJsonPrefix(prefix string) *Engine
- func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (engine *Engine) SetFuncMap(funcMap template.FuncMap)
- func (engine *Engine) SetHTMLTemplate(templ *template.Template)
- func (engine *Engine) Use(middleware ...HandlerFunc) IRoute
- type Error
- type ErrorType
- type H
- type HandlerFunc
- func BasicAuth(accounts Accounts) HandlerFunc
- func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc
- func Bind(val interface{}) HandlerFunc
- func CustomRecovery(handle RecoveryFunc) HandlerFunc
- func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc
- func ErrorLogger() HandlerFunc
- func ErrorLoggerT(typ ErrorType) HandlerFunc
- func Logger() HandlerFunc
- func LoggerWithConfig(conf LoggerConfig) HandlerFunc
- func LoggerWithFormatter(f LogFormatter) HandlerFunc
- func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc
- func Recovery() HandlerFunc
- func RecoveryWithWriter(out io.Writer, recovery ...RecoveryFunc) HandlerFunc
- func WrapF(f http.HandlerFunc) HandlerFunc
- func WrapH(h http.Handler) HandlerFunc
- type HandlersChain
- type ILogger
- type IResponseWriter
- type IRoute
- type IRouter
- type LogFormatter
- type LogFormatterParams
- type LogLevel
- type LoggerConfig
- type Negotiate
- type Param
- type Params
- type RecoveryFunc
- type RouteInfo
- type RouterGroup
- func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoute
- func (group *RouterGroup) BasePath() string
- func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) IRoute
- func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoute
- func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup
- func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRoute
- func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoute
- func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoute
- func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) IRoute
- func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoute
- func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) IRoute
- func (group *RouterGroup) Static(relativePath, root string) IRoute
- func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoute
- func (group *RouterGroup) StaticFile(relativePath, filepath string) IRoute
- func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoute
- type RoutesInfo
- type SimpleLogger
- func (s *SimpleLogger) Debug(v ...interface{})
- func (s *SimpleLogger) Debugf(format string, v ...interface{})
- func (s *SimpleLogger) Error(v ...interface{})
- func (s *SimpleLogger) Errorf(format string, v ...interface{})
- func (s *SimpleLogger) Info(v ...interface{})
- func (s *SimpleLogger) Infof(format string, v ...interface{})
- func (s *SimpleLogger) Level() LogLevel
- func (s *SimpleLogger) SetLevel(l LogLevel)
- func (s *SimpleLogger) Warn(v ...interface{})
- func (s *SimpleLogger) Warnf(format string, v ...interface{})
Constants ¶
const ( MiMeJSON = bind.MiMeJSON MiMeHTML = bind.MiMeHTML MiMeXML = bind.MiMeXML MiMeXML2 = bind.MiMeXML2 MiMePlain = bind.MiMePlain MiMePOSTForm = bind.MiMePOSTForm MiMeMultipartPOSTForm = bind.MiMeMultipartPOSTForm MiMeYAML = bind.MiMeYAML )
最常见的数据格式的 Content-Type MIME。
const ( DefaultLogPrefix = "[gin]" DefaultLogFlag = log.Ldate | log.Lmicroseconds DefaultLogLevel = LogDebug )
default log options
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 AuthUserKey = "user"
AuthUserKey is the cookie name for user credential in basic auth.
const BindKey = "_gin-gonic/gin/bindkey"
BindKey indicates a default bind key.
const (
// BodyBytesKey 表示默认的主体字节密钥。
BodyBytesKey = "_gin-gonic/gin/bodybyteskey"
)
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 CreateTestContext ¶
func CreateTestContext(w http.ResponseWriter) (c *Context, r *Engine)
CreateTestContext returns a fresh engine and context for testing purposes
func Dir ¶
func Dir(root string, listDirectory bool) http.FileSystem
Dir returns a http.Filesystem that can be used by http.FileServer(). It is used internally in router.Static(). if listDirectory == true, then it works the same as http.Dir() otherwise it returns a filesystem that prevents http.FileServer() to list the directory files.
func DisableBindValidation ¶
func DisableBindValidation()
DisableBindValidation closes the default validator.
func DisableConsoleColor ¶
func DisableConsoleColor()
DisableConsoleColor disables color output in the console.
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 ForceConsoleColor ¶
func ForceConsoleColor()
ForceConsoleColor force color output in the console.
func IsDebugging ¶
func IsDebugging() bool
IsDebugging returns true if the framework is running in debug mode. Use SetMode(gin.ReleaseMode) to disable debug mode.
Types ¶
type Context ¶
type Context struct { Request *http.Request // go 标准库中的 *http.Request Writer IResponseWriter // 自定义的 IResponseWriter 接口。 Params Params Keys map[string]interface{} // Keys 键是专门用于每个请求上下文的键值对。 Errors errorMsgs // Errors 使用此上下文的所有处理程序中间件附带的错误列表。 Accepted []string // Accepted 用于内容协商的手动接受格式的列表。 // contains filtered or unexported fields }
Context 封装 *http.Request 和 http.ResponseWriter。
请求和响应相关的逻辑都由 Context 模块承载。
func (*Context) Abort ¶
func (c *Context) Abort()
Abort 防止挂起的处理程序被调用。请注意,这不会停止当前的处理程序。
假设您有一个授权中间件,用于验证当前请求是否得到授权。 如果授权失败(例如:密码不匹配),则调用Abort以确保不调用此请求的其余处理程序。
func (*Context) AbortWithError ¶
AbortWithError 内部调用 *Context.AbortWithStatus() 和 *Context.Error()。
此方法停止链,写入状态代码,并将指定的错误推送到 *Context.Error()。有关更多详细信息,请参见 Context.Error()。
func (*Context) AbortWithStatus ¶
AbortWithStatus 调用 Abort() 并使用指定的状态代码写入标头。
例如,对请求进行身份验证的失败尝试可以使用:context.AbortWithStatus(401)。
func (*Context) AbortWithStatusJSON ¶
AbortWithStatusJSON 在内部调用 *Context.Abort(),然后调用 *Context.JSON()。
此方法停止链,写入状态代码并返回JSON正文。还将 Content-Type 设置为" application/json"。
func (*Context) AsciiJSON ¶
AsciiJSON 使用 Unicode 到 ASCII 字符串将给定结构体以JSON序列化到响应主体中。
还将 Content-Type 设置为 "application/json"。
func (*Context) BindWith ¶
BindWith binds the passed struct pointer using the specified binding engine. See the binding package.
func (*Context) CORS ¶
func (c *Context) CORS() HandlerFunc
func (*Context) ClientIP ¶
ClientIP implements a best effort algorithm to return the real client IP, it parses X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy. Use X-Forwarded-For before X-Real-Ip as nginx uses X-Real-Ip with the proxy's IP.
func (*Context) ContentType ¶
ContentType 返回请求的Content-Type标头。
func (*Context) Cookie ¶
Cookie 返回请求中提供的命名 cookie,如果找不到,则返回ErrNoCookie。
并返回已命名的cookie,并且不对其进行转义。如果多个Cookie与给定名称匹配,则仅返回一个Cookie。
func (*Context) Copy ¶
Copy 返回当前 *Context 的副本,该副本可以在请求范围之外安全地使用。
当 *Context 必须传递给 goroutine 时,必须使用此方法。
func (*Context) DataFromReader ¶
func (c *Context) DataFromReader(code int, contentLength int64, contentType string, reader io.Reader, extraHeaders map[string]string)
DataFromReader 将指定的Render写入主体流并更新HTTP代码。
func (*Context) DefaultPostForm ¶
DefaultPostForm 如果存在,则以POST url/encoded 形式或多部分形式返回指定的键,否则返回指定的 defaultValue 字符串。
有关更多信息,请参见:*Context.PostForm() 和 *Context.GetPostForm()。
func (*Context) DefaultQuery ¶
DefaultQuery returns the keyed url query value if it exists, otherwise it returns the specified defaultValue string. See: Query() and GetQuery() for further information.
GET /?name=Manu&lastname= c.DefaultQuery("name", "unknown") == "Manu" c.DefaultQuery("id", "none") == "none" c.DefaultQuery("lastname", "none") == ""
func (*Context) Done ¶
func (c *Context) Done() <-chan struct{}
Done 总是返回nil (chan将永远等待),如果要在关闭连接时中止工作,则应改用 Request.Context().Done()。
func (*Context) Error ¶
Error 将错误附加到当前 *Context。错误被推送到错误列表。
对于请求解析期间发生的每个错误,最好都调用 Error。 中间件可用于收集所有错误并将它们一起推送到数据库,打印日志或将其附加到HTTP响应中。 如果err为nil,err 将 panic。
func (*Context) FileAttachment ¶
FileAttachment 以一种有效的方式将指定的文件写入主体流中在客户端,通常将使用给定的文件名下载该文件。
func (*Context) FileFromFS ¶
func (c *Context) FileFromFS(filepath string, fs http.FileSystem)
FileFromFS 将http.FileSystem中的指定文件以高效的方式写入主体流。
func (*Context) FormFile ¶
func (c *Context) FormFile(name string) (*multipart.FileHeader, error)
FormFile 返回提供的表单密钥的第一个文件。
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) 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) GetPostForm ¶
GetPostForm 就像 *Context.PostForm(key)。
当它存在 (value,true)(即使值是一个空字符串)时,它从POST url/encode形式或多部分形式返回指定的键,否则返回(" ",false)。 例如,在PATCH请求中更新用户的电子邮件期间: email=mail@example.com --> ("mail@example.com", true) := GetPostForm("email") // set email to "mail@example.com" email= --> ("", true) := GetPostForm("email") // set email to "" --> ("", false) := GetPostForm("email") // do nothing with email
func (*Context) GetPostFormArray ¶
GetPostFormArray 返回给定形式键的字符串切片,以及一个布尔值(无论给定键是否存在至少一个值)。
func (*Context) GetPostFormMap ¶
GetPostFormMap 返回给定表单键的映射,以及一个布尔值(无论该给定键是否存在至少一个值),然后返回一个布尔值。
func (*Context) GetQuery ¶
GetQuery 就像Query()一样。
如果存在(value,true)(即使该值是一个空字符串),它也会返回键控的url查询值,否则将返回(" ",false)。 这是 *Context.Request.URL.Query().Get(key) 的快捷方式。 GET /?name=Manu&lastname= ("Manu", true) == c.GetQuery("name") ("", false) == c.GetQuery("id") ("", true) == c.GetQuery("lastname")
func (*Context) GetQueryArray ¶
GetQueryArray returns a slice of strings for a given query key, plus a boolean value whether at least one value exists for the given key.
func (*Context) GetQueryMap ¶
GetQueryMap 返回给定查询键的映射,以及一个布尔值(是否存在至少一个给定键的值)的布尔值。
func (*Context) GetRawData ¶
GetRawData 返回流数据。其内部代码 ioutil.ReadAll(c.Request.Body)
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) HTML ¶
HTML 渲染由其文件名指定的HTTP模板。
它还会更新HTTP代码,并将 Content-Type 设置为 "text/html"。 See http://golang.org/doc/articles/wiki/
func (*Context) HandlerName ¶
HandlerName 返回主处理程序的名称。例如,如果处理程序为"handleGetUsers()",则此函数将返回"main.handleGetUsers"。
func (*Context) HandlerNames ¶
HandlerNames 按照 HandlerName()的语义,以降序返回此 *Context 的所有已注册处理程序的列表。
func (*Context) Header ¶
Header 是 *Context.Writer.Header().Set(key,value) 的智能快捷方式。
它在响应中写入标头。如果value ==" ",则此方法删除标头 *Context.Writer.Header().Del(key)
func (*Context) IndentedJSON ¶
IndentedJSON 将给定结构体序列化为漂亮的JSON(缩进+结束行)到响应主体中。
还将 Content-Type设置为 "application/json"。 警告:我们建议仅将其用于开发目的,因为打印漂亮的JSON会占用更多的CPU和带宽。请改用 Context.JSON()。
func (*Context) IsWebsocket ¶
IsWebsocket 如果请求标头指示客户端正在发起 Websocket 握手,则返回true。
func (*Context) JSONP ¶
JSONP 将给定结构体作为JSON序列化到响应主体中。
它将填充添加到响应主体,以从位于与客户端不同的域中的服务器请求数据。 还将 Content-Type 设置为 "application/javascript"。
func (*Context) MultipartForm ¶
MultipartForm 返回已解析的多部分表单,包括文件上传。
func (*Context) NegotiateFormat ¶
NegotiateFormat 返回可接受的接受格式。
func (*Context) Next ¶
func (c *Context) Next()
Next 应该只在中间件内部使用。
它在调用处理程序内的链中执行挂起的处理程序。(在中间件内部执行下一个 HandlerFunc) See example in GitHub.
func (*Context) Param ¶
Param 返回URL参数的值。这是 *Context.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) Parse ¶
Parse (原ShouldBind方法)底层调用的是 *Context.ParseOnce(obj, b)。
1、检查 Content-Type 以自动选择解析引擎。根据 "Content-Type"标头,使用不同的解析器: "application/json" --> JSON bind "application/xml" --> XML bind 否则->返回错误。 2、如果 Content-Type == " application/json" 使用JSON或XML作为JSON输入,它将请求的主体解析为JSON格式的数据。 它将json有效负载解码为指定为指针的结构。 类似于 *Context.Bind(),但是此方法未将响应状态代码设置为400,如果json无效,则中止。
func (*Context) ParseBody ¶
ParseBody (原ShouldBindBodyWith方法) 与 ParseOnce 相似,但是它将请求正文存储到上下文中,并在再次调用时重用。
注意: 此方法在绑定之前读取正文。因此,如果只需要调用一次,则应使用 ParseOnce 以获得更好的性能。
func (*Context) ParseOnce ¶
ParseOnce (原ShouldBindWith方法) 使用指定的绑定引擎绑定传递的struct指针。
1、用户可以自行选择绑定器,自行对出错处理。自行选择绑定器,这也意味着用户可以自己实现绑定器。 例如: 嫌弃默认的json处理是用官方的json处理包,嫌弃它慢,可以自己实现Binding接口。 2、保存在 <obj>中的请求参数,不能重用。该方法使用一次后,<obj>中的数据就被清空了。 如果要调用多次,并且要重用<obj>的请求参数,请使用 ParseBody
func (*Context) PostFormMap ¶
PostFormMap 返回给定表单键的映射。
func (*Context) PureJSON ¶
PureJSON 将给定结构体作为JSON序列化到响应主体中。
*Context.PureJSON() 与 *Context.JSON() 不同,PureJSON 不会用其unicode实体替换特殊的html字符。
func (*Context) Query ¶
Query 如果存在,则返回<key>的URL查询值,否则返回一个空字符串 " "。
这是 *Context.Request.URL.Query().Get(key)的快捷方式 GET /path?id=1234&name=Manu&value= c.Query("id") == "1234" c.Query("name") == "Manu" c.Query("value") == "" c.Query("wtf") == ""
func (*Context) QueryArray ¶
QueryArray returns a slice of strings for a given query key. The length of the slice depends on the number of params with the given key.
func (*Context) SaveUploadedFile ¶
func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error
SaveUploadedFile 将表单文件上传到特定的 <dst>。
func (*Context) SecureJSON ¶
SecureJSON 将给定的结构体作为Secure JSON序列化到响应主体中。 如果给定的结构体是数组值,则默认值在响应主体前加上 "while(1)"。还将 Content-Type 设置为 "application/json"。
func (*Context) SetAccepted ¶
SetAccepted 设置接受标头数据。
func (*Context) SetCookie ¶
func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)
SetCookie 将 Set-Cookie 标头添加到 ResponseWriter 的标头中。
提供的cookie必须具有有效的名称。无效的cookie可能会被静默删除。
func (*Context) SetSameSite ¶
SetSameSite with cookie
func (*Context) Value ¶
func (c *Context) Value(key interface{}) interface{}
Value 返回与此 *Context 关联的键值;如果没有值与键关联,则返回nil。使用相同的键连续调用Value会返回相同的结果。
type DiscardLogger ¶
type DiscardLogger struct{}
DiscardLogger don't log implementation for ILogger
func (DiscardLogger) Debug ¶
func (DiscardLogger) Debug(v ...interface{})
Debug empty implementation
func (DiscardLogger) Debugf ¶
func (DiscardLogger) Debugf(format string, v ...interface{})
Debugf empty implementation
func (DiscardLogger) Error ¶
func (DiscardLogger) Error(v ...interface{})
Error empty implementation
func (DiscardLogger) Errorf ¶
func (DiscardLogger) Errorf(format string, v ...interface{})
Errorf empty implementation
func (DiscardLogger) Infof ¶
func (DiscardLogger) Infof(format string, v ...interface{})
Infof empty implementation
func (DiscardLogger) SetLevel ¶
func (DiscardLogger) SetLevel(l LogLevel)
SetLevel empty implementation
func (DiscardLogger) Warnf ¶
func (DiscardLogger) Warnf(format string, v ...interface{})
Warnf empty implementation
type Engine ¶
type Engine struct { RouterGroup // 如果当前路由无法匹配,但存在带有(不带)尾部斜杠的路径处理程序,则启用自动重定向。 // 例如,如果请求了foo,但仅对foo存在路由,则将客户端重定向到foo,其中GET请求的HTTP状态代码为301,其他所有请求方法的状态为307。 RedirectTrailingSlash bool // 如果启用,则路由器将尝试修复当前请求路径(如果未为其注册句柄)。 // 首先删除多余的路径元素,例如..。之后,路由器对清除的路径进行不区分大小写的查找。 // 如果可以找到此路由的句柄,则路由器将重定向到更正路径,其中GET请求的状态代码为301,所有其他请求方法的状态代码为307。 // 例如,FOO和..Foo可以重定向到foo RedirectTrailingSlash 与该选项无关。 RedirectFixedPath bool // 如果启用,路由器将检查当前路由是否允许另一种方法,如果当前请求不能被路由。 // 如果是这种情况,则使用'Method Not Allowed' 和HTTP状态代码405回答请求。 // 如果不允许其他方法,则将请求委托给NotFound处理程序。 HandleMethodNotAllowed bool ForwardedByClientIP bool // 726 755如果启用,它将以'X-AppEngine ...'开头插入一些标头,以便与该PaaS更好地集成。 AppEngine bool // 如果启用,则将使用url.RawPath查找参数。 UseRawPath bool // 如果为true,则将不转义路径值。 // 如果 UseRawPath 为false(默认情况下),则 UnescapePathValues 实际上为true,因为将使用url.Path,而该URL已经被取消转义。 UnescapePathValues bool // 赋予http.Request的ParseMultipartForm方法调用的'maxMemory'参数的值。 MaxMultipartMemory int64 // RemoveExtraSlash 即使有额外的斜杠,也可以从URL解析参数. See the PR #1817 and issue #1644 RemoveExtraSlash bool HTMLRender render.IHTMLRender FuncMap template.FuncMap // contains filtered or unexported fields }
Engine 容器对象,整个框架的基础
func New ¶
func New() *Engine
New 返回一个新的空白Engine实例,不附加任何中间件。
默认情况下,配置为:
- RedirectTrailingSlash: true
- RedirectFixedPath: false
- HandleMethodNotAllowed: false
- ForwardedByClientIP: true
- UseRawPath: false
- UnescapePathValues: true
func (*Engine) HandleContext ¶
HandleContext re-enter 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 death with this, use wisely.
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... TODO.
func (*Engine) NoRoute ¶
func (engine *Engine) NoRoute(handlers ...HandlerFunc)
NoRoute adds handlers for NoRoute. It return 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) Run ¶
Run attaches the router to a http.Server and starts listening and serving HTTP requests. It is a shortcut for http.ListenAndServe(addr, router) Note: this method will block the calling goroutine indefinitely unless an error happens.
func (*Engine) RunFd ¶
RunFd attaches the router to a http.Server and starts listening and serving HTTP requests through the specified file descriptor. Note: this method will block the calling goroutine indefinitely unless an error happens.
func (*Engine) RunListener ¶
RunListener attaches the router to a http.Server and starts listening and serving HTTP requests through the specified net.Listener
func (*Engine) RunTLS ¶
RunTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests. It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router) Note: this method will block the calling goroutine indefinitely unless an error happens.
func (*Engine) RunUnix ¶
RunUnix attaches the router to a http.Server and starts listening and serving HTTP requests through the specified unix socket (ie. a file). Note: this method will block the calling goroutine indefinitely unless an error happens.
func (*Engine) SecureJsonPrefix ¶
SecureJsonPrefix sets the secureJSONPrefix used in Context.SecureJSON.
func (*Engine) ServeHTTP ¶
func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request)
ServeHTTP conforms to the http.Handler interface.
func (*Engine) SetFuncMap ¶
SetFuncMap sets the FuncMap used for template.FuncMap.
func (*Engine) SetHTMLTemplate ¶
SetHTMLTemplate associate a template with HTML renderer.
func (*Engine) Use ¶
func (engine *Engine) Use(middleware ...HandlerFunc) IRoute
Use 注册全局中间件。
调用 RouterGroup.Use()将 middleware... 添加到 RouterGroup.Handlers 中。
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 是(http.ResponseWriter,*http.Request)函数签名的扩展。
func BasicAuth ¶
func BasicAuth(accounts Accounts) HandlerFunc
BasicAuth returns a Basic HTTP Authorization middleware. It takes as argument a map[string]string where the key is the user name and the value is the password.
func BasicAuthForRealm ¶
func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc
BasicAuthForRealm returns a Basic HTTP Authorization middleware. It takes as arguments a map[string]string where the key is the user name and the value is the password, as well as the name of the Realm. If the realm is empty, "Authorization Required" will be used by default. (see http://tools.ietf.org/html/rfc2617#section-1.2)
func Bind ¶
func Bind(val interface{}) HandlerFunc
Bind is a helper function for given interface object and returns a Gin middleware.
func CustomRecovery ¶
func CustomRecovery(handle RecoveryFunc) HandlerFunc
CustomRecovery returns a middleware that recovers from any panics and calls the provided handle func to handle it.
func CustomRecoveryWithWriter ¶
func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc
CustomRecoveryWithWriter returns a middleware for a given writer that recovers from any panics and calls the provided handle func to handle it.
func ErrorLogger ¶
func ErrorLogger() HandlerFunc
ErrorLogger returns a handlerfunc for any error type.
func ErrorLoggerT ¶
func ErrorLoggerT(typ ErrorType) HandlerFunc
ErrorLoggerT returns a handlerfunc for a given error type.
func Logger ¶
func Logger() HandlerFunc
Logger instances a Logger middleware that will write the logs to gin.DefaultWriter. By default gin.DefaultWriter = os.Stdout.
func LoggerWithConfig ¶
func LoggerWithConfig(conf LoggerConfig) HandlerFunc
LoggerWithConfig instance a Logger middleware with config.
func LoggerWithFormatter ¶
func LoggerWithFormatter(f LogFormatter) HandlerFunc
LoggerWithFormatter instance a Logger middleware with the specified log format function.
func LoggerWithWriter ¶
func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc
LoggerWithWriter instance a Logger middleware with the specified writer buffer. Example: os.Stdout, a file opened in write mode, a socket...
func Recovery ¶
func Recovery() HandlerFunc
Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.
func RecoveryWithWriter ¶
func RecoveryWithWriter(out io.Writer, recovery ...RecoveryFunc) HandlerFunc
RecoveryWithWriter returns a middleware for a given writer that recovers from any panics and writes a 500 if there was one.
func WrapF ¶
func WrapF(f http.HandlerFunc) HandlerFunc
WrapF is a helper function for wrapping http.HandlerFunc and returns a Gin middleware.
func WrapH ¶
func WrapH(h http.Handler) HandlerFunc
WrapH is a helper function for wrapping http.Handler and returns a Gin middleware.
type HandlersChain ¶
type HandlersChain []HandlerFunc
HandlersChain 是 HandlerFunc 的集合。
即: HandlersChain 是一个容器,里面放的都是 func(*Context)。
func (HandlersChain) Last ¶
func (c HandlersChain) Last() HandlerFunc
Last 返回 HandlersChain 链(请求处理链)中的最后一个 HandlerFunc (请求处理程序),最后一个 HandlerFunc (请求处理程序)是主要的处理程序。
type ILogger ¶
type ILogger interface { Debug(v ...interface{}) Debugf(format string, v ...interface{}) Error(v ...interface{}) Errorf(format string, v ...interface{}) Info(v ...interface{}) Infof(format string, v ...interface{}) Warn(v ...interface{}) Warnf(format string, v ...interface{}) Level() LogLevel SetLevel(l LogLevel) }
Logger is a logger interface
type IResponseWriter ¶
type IResponseWriter interface { http.ResponseWriter // 官方的接口 http.Hijacker // Hijack()可以将HTTP对应的TCP连接取出,连接在Hijack()之后,HTTP的相关操作就会受到影响,调用方需要负责去关闭连接。https://liqiang.io/post/hijack-in-go http.Flusher // 允许HTTP处理程序将缓冲数据刷新到客户端。 http.CloseNotifier Status() int // 返回当前请求的HTTP响应状态代码。 Size() int // 返回已经写入响应http主体的字节数。 WriteStr(string) (int, error) // 将字符串写入响应主体。 Written() bool // 如果响应主体已经编写,则返回true。 WriteHeaderNow() // 响应体中强制写入http标头(状态代码+标头)。 Pusher() http.Pusher // 获取服务器推送的http.Pusher }
IResponseWriter 响应体回写数据的接口。
type IRoute ¶
type IRoute interface { Use(...HandlerFunc) IRoute Handle(string, string, ...HandlerFunc) IRoute Any(string, ...HandlerFunc) IRoute GET(string, ...HandlerFunc) IRoute POST(string, ...HandlerFunc) IRoute DELETE(string, ...HandlerFunc) IRoute PATCH(string, ...HandlerFunc) IRoute PUT(string, ...HandlerFunc) IRoute OPTIONS(string, ...HandlerFunc) IRoute HEAD(string, ...HandlerFunc) IRoute StaticFile(string, string) IRoute Static(string, string) IRoute StaticFS(string, http.FileSystem) IRoute }
IRoute 接口里放的是常用的路由器处理器。
type IRouter ¶
type IRouter interface { IRoute Group(string, ...HandlerFunc) *RouterGroup }
type LogFormatter ¶
type LogFormatter func(params LogFormatterParams) string
LogFormatter gives the signature of the formatter function passed to LoggerWithFormatter
type LogFormatterParams ¶
type LogFormatterParams struct { Request *http.Request // TimeStamp shows the time after the server returns a response. TimeStamp time.Time // StatusCode is HTTP response code. StatusCode int // Latency is how much time the server cost to process a certain request. Latency time.Duration // ClientIP equals Context's ClientIP method. ClientIP string // Method is the HTTP method given to the request. Method string // Path is a path the client requests. Path string // ErrorMessage is set if error has occurred in processing the request. ErrorMessage string // BodySize is the size of the Response Body BodySize int // Keys are the keys set on the request's context. Keys map[string]interface{} // contains filtered or unexported fields }
LogFormatterParams is the structure any formatter will be handed when time to log comes
func (*LogFormatterParams) IsOutputColor ¶
func (p *LogFormatterParams) IsOutputColor() bool
IsOutputColor indicates whether can colors be outputted to the log.
func (*LogFormatterParams) MethodColor ¶
func (p *LogFormatterParams) MethodColor() string
MethodColor is the ANSI color for appropriately logging http method to a terminal.
func (*LogFormatterParams) ResetColor ¶
func (p *LogFormatterParams) ResetColor() string
ResetColor resets all escape attributes.
func (*LogFormatterParams) StatusCodeColor ¶
func (p *LogFormatterParams) StatusCodeColor() string
StatusCodeColor is the ANSI color for appropriately logging http status code to a terminal.
type LoggerConfig ¶
type LoggerConfig struct { // Optional. Default value is gin.defaultLogFormatter Formatter LogFormatter // Output is a writer where logs are written. // Optional. Default value is gin.DefaultWriter. Output io.Writer // SkipPaths is a url path array which logs are not written. // Optional. SkipPaths []string }
LoggerConfig defines the config for Logger middleware.
type Negotiate ¶
type Negotiate struct { Offered []string HTMLName string HTMLData interface{} JSONData interface{} XMLData interface{} YAMLData interface{} Data interface{} }
Negotiate contains all negotiations data.
type Params ¶
type Params []Param
Params 是由路由器返回的Param-slice。
切片是有序的,第一个URL参数也是第一个切片值。 因此,通过索引读取值是安全的。
type RecoveryFunc ¶
type RecoveryFunc func(c *Context, err interface{})
RecoveryFunc defines the function passable to CustomRecovery.
type RouteInfo ¶
type RouteInfo struct { Method string Path string Handler string HandlerFunc HandlerFunc }
RouteInfo 表示请求路由的规范,其中包含方法和路径及其处理程序。
type RouterGroup ¶
type RouterGroup struct { Handlers HandlersChain // Handlers 存储着所有中间件 // contains filtered or unexported fields }
RouterGroup 路由组
func (*RouterGroup) Any ¶
func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoute
Any 注册与所有HTTP方法匹配的路由。
GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE.
func (*RouterGroup) BasePath ¶
func (group *RouterGroup) BasePath() string
BasePath 返回路由器组的基本路径。
例如: if v := router.Group("/rest/n/v1/api"), v.BasePath()的返回值是 "/rest/n/v1/api".
func (*RouterGroup) DELETE ¶
func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) IRoute
DELETE 是 router.Handle(“DELETE”,relativePath,handlers)的快捷方式。
func (*RouterGroup) GET ¶
func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoute
GET 是 router.Handle(“GET”,relativePath,handlers)的快捷方式。
func (*RouterGroup) Group ¶
func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup
Group 返回一个新生成的 *RouterGroup,用来分开每个路由组加载不一样的中间件。
注册路由组中间件之前要先调用此方法,先生成一个 *RouterGroup,然后在调用 *RouterGroup.Use()注册路由组中间件。 例如: group := g.Group("/test_group") group.Use(middleware.Test()){ group.GET("/test",handler.TestTool)//这里会最终路由和中间件以及handle方法一起写入树节点中 } 例如: 可以将使用通用中间件进行授权的所有路由进行分组。
func (*RouterGroup) HEAD ¶
func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRoute
HEAD 是 router.Handle("HEAD",relativePath,handlers)的快捷方式。
func (*RouterGroup) Handle ¶
func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoute
Handle 使用给定的路径和方法注册新的请求 HandlerFunc 和中间件。
func (*RouterGroup) OPTIONS ¶
func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoute
OPTIONS 是 router.Handle("OPTIONS",relativePath,handlers)的快捷方式。
func (*RouterGroup) PATCH ¶
func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) IRoute
PATCH 是 router.Handle("PATCH",relativePath,handlers)的快捷方式。
func (*RouterGroup) POST ¶
func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoute
POST 是 router.Handle("POST",relativePath,handlers)的快捷方式。
func (*RouterGroup) PUT ¶
func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) IRoute
PUT 是 router.Handle("PUT",relativePath,handlers)的快捷方式。
func (*RouterGroup) Static ¶
func (group *RouterGroup) Static(relativePath, root string) IRoute
Static 提供给定文件系统根目录下的文件。
内部使用http.FileServer,因此使用http.NotFound代替路由器的NotFound处理程序。
要使用操作系统的文件系统实现: use : router.Static("/static", "/var/www")
func (*RouterGroup) StaticFS ¶
func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoute
StaticFS 就像 Static() 一样工作,但是可以改用自定义 http.FileSystem。
Gin默认用户: gin.Dir()
func (*RouterGroup) StaticFile ¶
func (group *RouterGroup) StaticFile(relativePath, filepath string) IRoute
StaticFile 注册单个路由,以便为本地文件系统的单个文件提供服务。
例如: router.StaticFile("favicon.ico", "./resources/favicon.ico")
func (*RouterGroup) Use ¶
func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoute
Use 将中间件添加到 RouterGroup.Handlers 中。
type SimpleLogger ¶
type SimpleLogger struct { DEBUG *log.Logger ERR *log.Logger INFO *log.Logger WARN *log.Logger // contains filtered or unexported fields }
SimpleLogger is the default implment of ILogger
func NewSimpleLogger ¶
func NewSimpleLogger(out io.Writer) *SimpleLogger
NewSimpleLogger use a special io.Writer as logger output
func NewSimpleLogger2 ¶
func NewSimpleLogger2(out io.Writer, prefix string, flag int) *SimpleLogger
NewSimpleLogger2 let you customrize your logger prefix and flag
func NewSimpleLogger3 ¶
NewSimpleLogger3 let you customrize your logger prefix and flag and logLevel
func (*SimpleLogger) Debugf ¶
func (s *SimpleLogger) Debugf(format string, v ...interface{})
Debugf implement ILogger
func (*SimpleLogger) Errorf ¶
func (s *SimpleLogger) Errorf(format string, v ...interface{})
Errorf implement ILogger
func (*SimpleLogger) Infof ¶
func (s *SimpleLogger) Infof(format string, v ...interface{})
Infof implement ILogger
func (*SimpleLogger) SetLevel ¶
func (s *SimpleLogger) SetLevel(l LogLevel)
SetLevel implement ILogger
func (*SimpleLogger) Warnf ¶
func (s *SimpleLogger) Warnf(format string, v ...interface{})
Warnf implement ILogger