Documentation ¶
Overview ¶
Package gin implements a HTTP web framework called gin.
See https://gin-gonic.com/ for more information about gin.
1、中文文档: https://www.kancloud.cn/shuangdeyu/gin_book/949419
2、官方文档: https://github.com/gin-gonic/gin
3、启动一个Http服务:
func main() { r := gin.Default() 或者 r := gin.New() r.GET("/ping", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "pong", }) }) r.Run(":8080") // localhost:8080 }
Index ¶
- Constants
- Variables
- func AddGenOne(handleFuncName, routerPath string, methods []string)
- 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 FindTag(obj interface{}, field, tag string) string
- func ForceConsoleColor()
- func GetStringList(list []string) string
- func GetToken(c *Context) string
- func IsDebugging() bool
- func Mode() string
- func SetMode(value string)
- func UnMarshal(name string) string
- type APIFunc
- type Accounts
- type Base
- type BeforeAfter
- 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) ClientIP() string
- func (c *Context) ContentType() string
- func (c *Context) Cookie(name string) (string, error)
- func (c *Context) Copy() *Context
- func (c *Context) Cors() HandlerFunc
- 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) 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) FormMultipart() (*multipart.Form, 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) 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) IsAjax() 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) 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{}) (err 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) PostFormDefault(key, defaultValue 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) QueryDefault(key, defaultValue string) string
- func (c *Context) QueryMap(key string) map[string]string
- func (c *Context) Redirect(code int, location string)
- func (c *Context) RemoteIP() (net.IP, bool)
- func (c *Context) Render(code int, r render.Render)
- 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 DefaultBeforeAfter
- 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) New() *Base
- 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 ErrorFunc
- 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 Hook
- type IRoute
- type IRouter
- type JWTMiddleware
- func (mw *JWTMiddleware) CheckIfTokenExpire(c *Context) (jwt.MapClaims, error)
- func (mw *JWTMiddleware) GetClaimsFromJWT(c *Context) (MapClaims, error)
- func (mw *JWTMiddleware) Init() error
- func (mw *JWTMiddleware) LoginHandler(c *Context)
- func (mw *JWTMiddleware) LogoutHandler(c *Context)
- func (mw *JWTMiddleware) MiddlewareFunc() HandlerFunc
- func (mw *JWTMiddleware) ParseToken(c *Context) (*jwt.Token, error)
- func (mw *JWTMiddleware) ParseTokenStr(token string) (*jwt.Token, error)
- func (mw *JWTMiddleware) RefreshHandler(c *Context)
- func (mw *JWTMiddleware) RefreshToken(c *Context) (string, time.Time, error)
- func (mw *JWTMiddleware) TokenGenerate(data interface{}) (string, time.Time, error)
- type List
- type LogFormatter
- type LogFormatterParams
- type LoggerConfig
- type MapClaims
- type Negotiate
- type Param
- type Params
- type RecoveryFunc
- type RespBody
- type ResponseWriter
- 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
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 ( // 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 ( // ErrMissingSecretKey 表示需要密钥 ErrMissingSecretKey = errors.New("需要密钥") // ErrForbidden when HTTP status 403 is given ErrForbidden = errors.New("您无权访问此资源") // ErrMissingAuthFunc indicates Authenticator is required ErrMissingAuthFunc = errors.New(" JWTMiddleware.AuthFunc函数未定义!") // ErrMissingLoginValues indicates a user tried to authenticate without username or password ErrMissingLoginValues = errors.New("缺少用户名或密码") // ErrFailedAuthentication indicates authentication failed, could be faulty username or password ErrFailedAuthentication = errors.New("用户名或密码错误") // ErrFailedTokenCreation indicates JWT Token failed to create, reason unknown ErrFailedTokenCreation = errors.New("无法创建JWT Token") // ErrExpiredToken indicates JWT token has expired. Can't refresh. ErrExpiredToken = errors.New("token已过期") // ErrEmptyAuthHeader can be thrown if authing with a HTTP header, the Auth header needs to be set ErrEmptyAuthHeader = errors.New("auth标头为空") // ErrMissingExpField missing exp field in token ErrMissingExpField = errors.New("缺少exp字段") // ErrWrongFormatOfExp field must be float64 format ErrWrongFormatOfExp = errors.New("exp必须为float64格式") // ErrInvalidAuthHeader indicates auth header is invalid, could for example have the wrong Realm name ErrInvalidAuthHeader = errors.New("auth标头无效") // ErrEmptyQueryToken can be thrown if authing with URL Query, the query token variable is empty ErrEmptyQueryToken = errors.New("查询token为空") // ErrEmptyCookieToken can be thrown if authing with a cookie, the token cookie is empty ErrEmptyCookieToken = errors.New(" Cookie token为空") // ErrEmptyParamToken can be thrown if authing with parameter in path, the parameter in path is empty ErrEmptyParamToken = errors.New("参数token为空") // ErrInvalidSigningAlgorithm indicates signing algorithm is invalid, needs to be HS256, HS384, HS512, RS256, RS384 or RS512 ErrInvalidSigningAlgorithm = errors.New("无效签名算法") // ErrNoPrivateKeyFile indicates that the given private key is unreadable ErrNoPrivateKeyFile = errors.New("私钥文件不可读") // ErrNoPubKeyFile indicates that the given public key is unreadable ErrNoPubKeyFile = errors.New("公钥文件不可读") // ErrInvalidPrivateKey indicates that the given private key is invalid ErrInvalidPrivateKey = errors.New("私钥无效") // ErrInvalidPubKey indicates the the given public key is invalid ErrInvalidPubKey = errors.New("公钥无效") // IdentityKey default identity key IdentityKey = "identity" )
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 AddGenOne ¶ added in v1.7.2
添加路由 参数<handleFuncName>是路由处理函数的名称 <routerPath>是具体的路由 url 路径 <methods>是具体的请求方法
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 GetStringList ¶ added in v1.7.2
GetStringList format string
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 Base ¶ added in v1.7.2
type Base struct {
// contains filtered or unexported fields
}
type BeforeAfter ¶ added in v1.7.2
type BeforeAfter struct { C *Context FuncName string // 函数名 Param interface{} // 调用前的请求参数 Response interface{} // 调用后的返回数据 Error error Ctx context.Context // 占位参数,可用于存储其他参数,前后连接可用 }
对象调用前后执行中间件参数
type Context ¶
type Context struct { Request *http.Request // go 标准库中的 *http.Request Writer ResponseWriter Params Params Keys map[string]interface{} // Keys 键是专门用于每个请求上下文的键值对。 Errors errorMsgs // Errors 使用此上下文的所有处理程序中间件附带的错误列表。 Accepted []string // Accepted 用于内容协商的手动接受格式的列表。 // contains filtered or unexported fields }
Context 封装 *http.Request 和 http.ResponseWriter。
1、请求和响应相关的逻辑都由 Context 模块承载。 2、获取 URL路径 中的请求参数: Param() Query() QueryDefault() QueryArray() QueryMap() 以及 GetXXX()系列方法。这些方法可以用在 GET、POST 请求中。 3、获取 Request.Body表单 中的请求参数: PostForm() PostFormDefault() PostFormArray() PostFormMap() FormFile() FormMultipart()。这些方法都不能用在 GET 请求中。 4、解析 请求参数到结构体中(只有3个): Parse() ParseBody() ParseUri()
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) ClientIP ¶
ClientIP 以返回真实的客户端IP 它在后台调用了c.RemoteIP(),以检查远程IP是否是受信任的代理。 如果是,它将尝试解析在Engine.RemoteIPHeaders中定义的标头(默认为[X-Forwarded-For,X-Real-Ip])。 如果标头在语法上无效,或者远程IP与信任的代理不对应,则返回远程IP(来自Request.RemoteAddr)。
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) 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 获取 POST 请求中的单个文件。每次只能获取一个文件。这个方法不能用于 GET 请求。
详细文档: https://www.kancloud.cn/shuangdeyu/gin_book/949420
func (*Context) FormMultipart ¶
FormMultipart (原MultipartForm) 获取 POST 请求中的多部分表单,包括多个文件上传。每次能获取多个文件。
详细文档: https://www.kancloud.cn/shuangdeyu/gin_book/949420
func (*Context) FullPath ¶
FullPath 返回匹配的路由完整路径。对于未找到的路由,返回一个空字符串。
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) 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) NegotiateFormat ¶
NegotiateFormat 返回可接受的接受格式。
func (*Context) Next ¶
func (c *Context) Next()
Next 这个方法只在中间件内部使用。
它在调用处理程序内的链中执行挂起的处理程序。 See example in GitHub.
func (*Context) Param ¶
Param 获取URL路径中的 URL参数。
1、既可以用在GET请求中,也可以用在POST请求中。 2、如果存在,则返回<key>的URL的参数值,否则返回一个空字符串。 3、注意:这并不是获取查询参数。 router.GET("/user/:id", func(c *gin.Context) { id := c.Param("id") }) 详细文档: https://www.kancloud.cn/shuangdeyu/gin_book/949416
func (*Context) Parse ¶
Parse (原ShouldBind方法)将请求参数解析到<obj>中,参数<obj>必须是指针类型!
1、检查 Content-Type 以自动选择解析引擎。根据 "Content-Type"标头,使用不同的解析器: "application/json" --> JSON bind "application/xml" --> XML bind 否则->返回错误。 2、如果 Content-Type == " application/json" 则:它将请求的主体解析为JSON格式的数据。 3、保存在 <obj>中的请求参数,不能重用。该方法使用一次后,<obj>中的数据就被清空了。 如果要调用多次,并且要重用<obj>的请求参数,请使用 ParseBody
func (*Context) ParseBody ¶
ParseBody 将请求参数解析到<obj>中,适用于重复解析。参数<obj>必须是指针类型!
1、ParseBody 与 Parse 相似,唯一区别: ParseBody 会将请求正文存储到上下文中,并在再次调用时重用。 2、注意: 此方法在解析之前读取正文。因此,如果只需要调用一次,则应使用 Parse 以获得更好的性能。 (原ShouldBindBodyWith方法)测试用例 https://www.jianshu.com/p/0f0bf53bedd2
func (*Context) PostForm ¶
PostForm 获取 POST 请求中的表单参数。注意: 这个方法不能用于 GET 请求。
如果存在,则以 POST url/encoded 形式或多部分形式返回 key对应的value,否则返回一个空字符串。 详细文档: https://www.kancloud.cn/shuangdeyu/gin_book/949418
func (*Context) PostFormArray ¶
PostFormArray 获取 POST 请求中的参数。注意: 这个方法不能用于 GET 请求。
返回给定表单键的字符串切片。切片的长度取决于具有给定键的参数的数量。
func (*Context) PostFormDefault ¶
PostFormDefault 获取 POST 请求中的参数。注意: 这个方法不能用于 GET 请求。
如果存在,则以 POST urlencoded 形式或多部分形式返回 key对应的value,否则返回指定的 defaultValue 字符串。
func (*Context) PureJSON ¶
PureJSON 将给定结构体作为JSON序列化到响应主体中。
*Context.PureJSON() 与 *Context.JSON() 不同,PureJSON 不会用其unicode实体替换特殊的html字符。
func (*Context) Query ¶
Query: 获取URL路径中的 查询参数。
1、既可以用在GET请求中,也可以用在POST请求中。 2、如果存在,则返回<key>的URL查询值,否则返回一个空字符串。 3、注意:这并不是获取URL参数。 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 获取 GET 请求中的参数。返回给定查询键的字符串切片。切片的长度取决于给定关键字的参数数量。
URL查询参数,就是一个数组,例如: URL是这样 ?a=b&a=c&a=d,key值都一样,但是对应的value不一样。 例如: URL: /?media=blog&media=wechat,它们的 key 都是 media。 返回: ["blog","wechat"] 详细文档: https://www.flysnow.org/2019/12/18/golang-gin-query-parameters-array-map.html
func (*Context) QueryDefault ¶
QueryDefault 获取 GET 请求中的参数。返回键入的url查询值(如果存在),否则返回指定的defaultValue字符串。
例如: GET /?name=Manu&lastname= c.DefaultQuery("name", "unknown") == "Manu" c.DefaultQuery("id", "none") == "none" c.DefaultQuery("lastname", "none") == "" 详细文档: https://www.kancloud.cn/shuangdeyu/gin_book/949417
func (*Context) QueryMap ¶
QueryMap 获取 GET 请求中的参数。返回给定查询键的字符串字典。
其实就是把满足一定格式的URL查询参数,转换为一个map。 例如: URL: /?ids[a]=123&ids[b]=456&ids[c]=789 返回: {"a":"123","b":"456","c":"789"} 详细文档: https://www.flysnow.org/2019/12/18/golang-gin-query-parameters-array-map.html
func (*Context) RemoteIP ¶
RemoteIP parses the IP from Request.RemoteAddr, normalizes and returns the IP (without the port). It also checks if the remoteIP is a trusted proxy or not. In order to perform this validation, it will see if the IP is contained within at least one of the CIDR blocks defined in Engine.TrustedProxies
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 DefaultBeforeAfter ¶ added in v1.7.2
type DefaultBeforeAfter struct{}
func (*DefaultBeforeAfter) After ¶ added in v1.7.2
func (d *DefaultBeforeAfter) After(r *BeforeAfter) bool
call之后调用
func (*DefaultBeforeAfter) Before ¶ added in v1.7.2
func (d *DefaultBeforeAfter) Before(r *BeforeAfter) bool
call之前调用
type Engine ¶
type Engine struct { RouterGroup // 1、如果当前路由无法匹配,但存在带有(不带)尾部斜杠的路径处理程序,则启用自动重定向。 // 2、例如,如果请求了foo,但仅对foo存在路由,则将客户端重定向到foo,其中GET请求的HTTP状态代码为301,其他所有请求方法的状态为307。 RedirectTrailingSlash bool // 1、如果启用,则路由器将尝试修复当前请求路径(如果未为其注册句柄)。 // 2、首先删除多余的路径元素,例如..。之后,路由器对清除的路径进行不区分大小写的查找。 // 3、如果可以找到此路由的句柄,则路由器将重定向到更正路径,其中GET请求的状态代码为301,所有其他请求方法的状态代码为307。 // 4、例如,FOO和..Foo可以重定向到foo RedirectTrailingSlash 与该选项无关。 RedirectFixedPath bool // 1、如果启用,路由器将检查当前路由是否允许另一种方法,如果当前请求不能被路由。 // 2、如果是这种情况,则使用'Method Not Allowed' 和HTTP状态代码405回答请求。 // 3、如果不允许其他方法,则将请求委托给NotFound处理程序。 HandleMethodNotAllowed bool // 1、如果启用,将从请求的标头解析客户端IP,该标头与存储在((gin.Engine).RemoteIPHeaders`上的标头匹配)。 // 2、如果没有获取任何IP,它将回退到从(gin.Context).Request.RemoteAddr`获得的IP。 ForwardedByClientIP bool // 当(gin.Engine).ForwardedByClientIP`为true且(gin.Context).Request.RemoteAddr与至少一个网络源(gin)匹配时, // 用于获取客户端IP的标头列表。引擎)。TrustedProxies`。 RemoteIPHeaders []string // 当(gin.Engine).ForwardedByClientIP`为true时,信任包含其他客户端IP的请求标头的网络来源列表(IPv4地址,IPv4 CIDR,IPv6地址或IPv6 CIDR). TrustedProxies []string // 如果启用,它将信任以"X-AppEngine ..."开头的某些标头,以便与该PaaS更好地集成。 AppEngine bool // 如果启用,则将使用url.RawPath查找参数。 UseRawPath bool // 1、如果为true,则将不转义路径值。 // 2、如果UseRawPath为false(默认情况下),则UnescapePathValues实际上为true,因为将使用url.Path,而该URL已经未被转义。 UnescapePathValues bool // 赋予http.Request的ParseMultipartForm方法调用的'maxMemory'参数的值。 MaxMultipartMemory int64 // 即使有额外的斜杠,也可以从URL解析参数。 // See the PR #1817 and issue #1644 RemoveExtraSlash bool HTMLRender render.HTMLRender FuncMap template.FuncMap // contains filtered or unexported fields }
Engine 是框架的实例,它包含多路复用器,中间件和配置设置。
New() or Default() 能创建一个 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 将全局中间件附加到路由器。
通过 Use() 附加的中间件将包含在每个单个请求的处理程序链中。 甚至404、405,静态文件...例如,这也是记录器或错误管理中间件的正确位置。
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 Hook ¶ added in v1.7.2
type Hook interface { Before(r *BeforeAfter) bool After(r *BeforeAfter) bool }
对象调用前后执行中间件(支持总的跟对象单独添加)
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 }
IRoutes 接口里放的是常用的路由器处理器。
type IRouter ¶
type IRouter interface { IRoute //单点路由 Group(string, ...HandlerFunc) *RouterGroup //路由组 }
IRouter 定义所有路由器句柄接口,包括单路由器和组路由器。
type JWTMiddleware ¶ added in v1.7.2
type JWTMiddleware struct { Realm string //显示给用户的名称,(必须参数) SigningAlgorithm string //(可选参数)签名算法-可能的值为HS256,HS384,HS512,RS256,RS384或RS512,默认为HS256。 Key []byte //用于签名的密钥 Timeout time.Duration //jwt令牌有效的持续时间。可选,默认为一小时。 //(可选参数)该字段允许客户端刷新令牌,直到MaxRefresh通过。 // 请注意:客户端可以在MaxRefresh的最后时刻刷新其令牌。 // 这意味着令牌的最大有效时间跨度为TokenTime + MaxRefresh。 // 默认为0表示不可刷新。 MaxRefresh time.Duration //(必须参数)基于登录信息执行用户身份验证的回调函数。 // 必须返回用户数据作为用户标识符,它将存储在Claim Array中。 AuthFunc func(c *Context) (interface{}, error) //(可选参数)回调功能,应执行经过身份验证的用户的授权。仅在身份验证成功后调用。 // 成功时必须返回true,失败时必须返回false。默认为成功。 AuthAfter func(data interface{}, c *Context) bool //登录期间将调用的回调函数。 // 使用此功能可以将其他有效负载数据添加到JWT Token // 然后在请求期间通过c.Get("JWT_PAYLOAD")使数据可用。 // 请注意,有效负载未加密。 // jwt.io上提到的属性不能用作map的键。 PayloadFunc func(data interface{}) MapClaims //用户可以定义自己的未经授权的功能。 UnAuthFunc func(*Context, int, string) //用户可以定义自己的 LoginResponse 函数。 LoginResponse func(*Context, int, string, time.Time) //用户可以定义自己的 LogoutResponse 函数。 LogoutResponse func(*Context, int) //用户可以定义自己的 RefreshResponse 函数。 RefreshResponse func(*Context, int, string, time.Time) //设置身份处理程序功能 IdentityHandler func(*Context) interface{} // 设置身份密钥 IdentityKey string //(可选参数)是"<source>:<name>"形式的字符串,用于从请求中提取令牌。(默认值"header:Authorization") //可选值: // - "header:<name>" // - "query:<name>" // - "cookie:<name>" TokenLookup string //标头中的字符串。默认值为"Bearer" TokenHeadName string // TimeFunc 提供当前时间。您可以覆盖它以使用其他时间值。这对于测试或服务器使用不同于令牌的时区很有用。 TimeFunc func() time.Time // 当JWT中间件发生故障时的HTTP状态消息。 HTTPStatusMsgFunc func(e error, c *Context) string // 非对称算法的私钥文件 PrivateKeyFile string //非对称算法的私钥字节 // 注意:如果同时设置了PrivateKeyFile,则PrivateKeyFile优先于PrivateKeyByte PrivateKeyByte []byte // 非对称算法的公钥文件 PubKeyFile string // 非对称算法的公钥字节。 // 注意:如果同时设置了 PubKeyFile,则 PubKeyFile 优先于 PubKeyByte PubKeyByte []byte // (可选)将Token作为Cookie返回 SendCookie bool // Cookie有效的持续时间。可选,默认情况下等于 Timeout 的值。 CookieMaxAge time.Duration // 允许不安全的Cookie通过HTTP进行开发 SecureCookie bool // 允许访问客户端的Cookie进行开发 CookieHTTPOnly bool // 允许更改Cookie域以进行开发 CookieDomain string // SendAuthorization 允许每个请求的返回授权标头 SendAuthorization bool // 禁用上下文的abort()。 DisabledAbort bool // CookieName 允许更改Cookie名称以进行开发 CookieName string // CookieSameSite 允许使用http.SameSite Cookie参数 CookieSameSite http.SameSite // contains filtered or unexported fields }
提供了Json-Web-Token身份验证实现。失败时,将返回401 HTTP响应.
成功后,将调用包装的中间件,并以c.Get("userID").(string)的形式提供userID。 用户可以通过将json请求发布到LoginHandler来获得令牌。然后需要在Authentication标头中传递令牌 例如:Authorization:Bearer XXX_TOKEN_XXX
func NewJWT ¶ added in v1.7.2
func NewJWT(m *JWTMiddleware) (*JWTMiddleware, error)
New for check error with GinJWTMiddleware
func (*JWTMiddleware) CheckIfTokenExpire ¶ added in v1.7.2
func (mw *JWTMiddleware) CheckIfTokenExpire(c *Context) (jwt.MapClaims, error)
CheckIfTokenExpire 检查token是否过期
func (*JWTMiddleware) GetClaimsFromJWT ¶ added in v1.7.2
func (mw *JWTMiddleware) GetClaimsFromJWT(c *Context) (MapClaims, error)
GetClaimsFromJWT get claims from JWT token
func (*JWTMiddleware) Init ¶ added in v1.7.2
func (mw *JWTMiddleware) Init() error
MiddlewareInit initialize jwt configs.
func (*JWTMiddleware) LoginHandler ¶ added in v1.7.2
func (mw *JWTMiddleware) LoginHandler(c *Context)
LoginHandler 可以被客户端用来获取jwt令牌。
有效负载必须为{"username":"username","password":"password"}形式的json。 回复的格式为{"token":"token"}。
func (*JWTMiddleware) LogoutHandler ¶ added in v1.7.2
func (mw *JWTMiddleware) LogoutHandler(c *Context)
LogoutHandler 可以被客户端用来删除jwt cookie(如果已设置)
func (*JWTMiddleware) MiddlewareFunc ¶ added in v1.7.2
func (mw *JWTMiddleware) MiddlewareFunc() HandlerFunc
MiddlewareFunc 使 JWTMiddleware 实现 Middleware 接口。
func (*JWTMiddleware) ParseToken ¶ added in v1.7.2
func (mw *JWTMiddleware) ParseToken(c *Context) (*jwt.Token, error)
ParseToken 从 gin.Context 解析jwt令牌
func (*JWTMiddleware) ParseTokenStr ¶ added in v1.7.2
func (mw *JWTMiddleware) ParseTokenStr(token string) (*jwt.Token, error)
ParseTokenString 解析jwt token字符串
func (*JWTMiddleware) RefreshHandler ¶ added in v1.7.2
func (mw *JWTMiddleware) RefreshHandler(c *Context)
RefreshHandler 可用于刷新token。token在刷新时仍然需要有效。
应放置在使用 JWTMiddleware 的端点下。 回复的格式为{"token":"token"}。
func (*JWTMiddleware) RefreshToken ¶ added in v1.7.2
RefreshToken 刷新token并检查token是否过期
func (*JWTMiddleware) TokenGenerate ¶ added in v1.7.2
func (mw *JWTMiddleware) TokenGenerate(data interface{}) (string, time.Time, error)
TokenGenerator 客户端可以用来获取jwt token的方法。
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 MapClaims ¶ added in v1.7.2
type MapClaims map[string]interface{}
使用 map[string]interface {}进行JSON解码,(默认的声明类型)
func ExtractClaims ¶ added in v1.7.2
ExtractClaims 帮助提取JWT的Claims
func ExtractClaimsFromToken ¶ added in v1.7.2
func ExtractClaimsFromToken(token *jwt.Token) MapClaims
ExtractClaimsFromToken 帮助从token中提取JWT Claims
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 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 RecoveryFunc ¶
type RecoveryFunc func(c *Context, err interface{})
RecoveryFunc defines the function passable to CustomRecovery.
type ResponseWriter ¶
type ResponseWriter interface { http.ResponseWriter http.Hijacker http.Flusher http.CloseNotifier // 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 // Writes the string into the response body. WriteString(string) (int, error) // Returns true if the response body was already written. Written() bool // Forces to write the http header (status code + headers). WriteHeaderNow() // get the http.Pusher for server push Pusher() http.Pusher }
ResponseWriter ...
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 在内部用于配置路由器,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 返回路由器组的基本路径。
For example, if v := router.Group("/rest/n/v1/api"), v.BasePath() is "/rest/n/v1/api".
func (*RouterGroup) DELETE ¶
func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) IRoute
DELETE is a shortcut for router.Handle("DELETE", path, handle).
func (*RouterGroup) GET ¶
func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoute
GET is a shortcut for router.Handle("GET", path, handle).
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 is a shortcut for router.Handle("HEAD", path, handle).
func (*RouterGroup) Handle ¶
func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoute
Handle 使用给定的路径和方法注册新的请求句柄和中间件。
最后一个处理程序应该是真正的处理程序,其他处理程序应该是可以并且应该在不同路由之间共享的中间件。请参阅GitHub中的示例代码。 对于GET,POST,PUT,PATCH和DELETE请求,可以使用相应的快捷功能。 此功能用于批量加载,并允许使用不常用的,非标准化或自定义的方法(例如,用于与代理进行内部通信)。
func (*RouterGroup) OPTIONS ¶
func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoute
OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle).
func (*RouterGroup) PATCH ¶
func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) IRoute
PATCH is a shortcut for router.Handle("PATCH", path, handle).
func (*RouterGroup) POST ¶
func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoute
POST is a shortcut for router.Handle("POST", path, handle).
func (*RouterGroup) PUT ¶
func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) IRoute
PUT is a shortcut for router.Handle("PUT", path, handle).
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 中。