文档:https://godoc.org/github.com/gin-gonic/gin

常量

  1. const (
  2. // DebugMode indicates gin mode is debug.
  3. DebugMode = "debug"
  4. // ReleaseMode indicates gin mode is release.
  5. ReleaseMode = "release"
  6. // TestMode indicates gin mode is test.
  7. TestMode = "test"
  8. )

Variables

  1. 日志输出格式:
  2. var DebugPrintRouteFunc func(httpMethod, absolutePath, handlerName string, nuHandlers int)
  3. 默认的日志输出方式:
  4. var DefaultWriter io.Writer = os.Stdout

包函数

func Dir(root string, listDirectory bool) http.FileSystem

  • Dir返回一个http.FileSystem可以由http.FileServer()使用的文件系统。它在router.Static()中内部使用。如果listDirectory == true,那么它的工作原理与http.Dir()相同,否则它返回一个文件系统,该文件系统阻止http.FileServer()列出目录文件。

func DisableBindValidation():关闭默认验证器
func DisableConsoleColor():禁用控制台中使用颜色
func ForceConsoleColor():强制控制台中的使用颜色
func IsDebugging()bool:是否处于Debug模式
func Mode() string:返回当前gin模式
func SetMode(value string):设置gin模式

type Engine

  1. type Engine struct {
  2. RouterGroup
  3. // 默认开启,自动重定向
  4. // 如果/foo/被请求,但是一个路由只存在于/foo,客户端会被重定向到/foo
  5. RedirectTrailingSlash bool
  6. // 默认不开启,如果启动,删除多余的/,并不区分大小写进行路由
  7. // 如://FOO 可以路由到/foo
  8. RedirectFixedPath bool
  9. // 默认不开启,如果启动,当路由不到时,返回Method Not Allowed,状态码405,而不是常规的404
  10. HandleMethodNotAllowed bool
  11. //默认开启
  12. ForwardedByClientIP bool
  13. // 如果启用,它会插入一些以“X-AppEngine…”为了更好地融入PaaS。
  14. AppEngine bool
  15. // 默认不开启,如果启用,url.RawPath将用于查找参数.
  16. UseRawPath bool
  17. //默认开启
  18. If true, the path value will be unescaped.
  19. If UseRawPath is false (by default), the UnescapePathValues effectively is true,
  20. as url.Path gonna be used, which is already unescaped.
  21. UnescapePathValues bool
  22. // 连接最大使用的缓存
  23. MaxMultipartMemory int64
  24. HTMLRender render.HTMLRender
  25. FuncMap template.FuncMap
  26. ...
  27. }

unc Default() Engine:默认引擎,包含日志记录器和恢复中间件
func New()
Engine:空白引擎
func (engine Engine) LoadHTMLFiles(files …string):加载HTML文件并与HTML渲染器相关联
func (engine
Engine) LoadHTMLGlob(pattern string):加载glob模式标识的HTML文件,并与HTML渲染器关联
func (engine Engine) Run(addr …string) (err error):运行,监听http
func (engine
Engine) RunTLS(addr, certFile, keyFile string) (err error):运行,监听https
func (engine *Engine) NoMethod(handlers …HandlerFunc) 添加405处理程序

  • 如果只想返回405代码,将Engine.HandleMethodNotAllowed 设置为true即可,默认的会返回404

func (engine Engine) NoRoute(handlers …HandlerFunc) 添加404处理程序。默认情况下,它返回404代码
func (engine
Engine) Use(middleware …HandlerFunc) IRoutes:注册中间键
func (engine Engine) LoadHTMLFiles(files …string):加载html文件切片
func (engine
Engine) LoadHTMLGlob(pattern string):加载符合表达式的所有文件

  1. router.LoadHTMLGlob("templates/*")

type RouterGroup

  1. type RouterGroup struct {
  2. Handlers HandlersChain
  3. // contains filtered or unexported fields
  4. }

func (group RouterGroup) Any(relativePath string, handlers …HandlerFunc) IRoutes
func (group
RouterGroup) Handle(httpMethod, relativePath string, handlers …HandlerFunc) IRoutes
func (group RouterGroup) GET(relativePath string, handlers …HandlerFunc) IRoutes
func (group
RouterGroup) POST(relativePath string, handlers …HandlerFunc) IRoutes
func (group RouterGroup) PUT(relativePath string, handlers …HandlerFunc) IRoutes
func (group
RouterGroup) PATCH(relativePath string, handlers …HandlerFunc) IRoutes
func (group RouterGroup) DELETE(relativePath string, handlers …HandlerFunc) IRoutes
func (group
RouterGroup) Static(relativePath, root string) IRoutes:加载一个文件夹所有静态文件
func (group RouterGroup) StaticFile(relativePath, filepath string) IRoutes:加载一个静态文件
func (group
RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes

  • 使用FileSystem加载静态文件。默认用户:gin.Dir()

func (group *RouterGroup) Use(middleware …HandlerFunc) IRoutes:为一个分组使用中间键

type H

  1. type H map[string]interface{}

type HandlerFunc

  1. type HandlerFunc func(*Context)

func ErrorLogger() HandlerFunc :为任何错误类型返回handlerfunc
func Logger() HandlerFunc

  • 实例化Logger中间件,将日志写入gin.DefaultWriter。默认情况下,gin.DefaultWriter = os.Stdout

func LoggerWithConfig(conf LoggerConfig) HandlerFunc 带有配置的日志程序中间件
func LoggerWithFormatter(f LogFormatter) HandlerFunc:返回具有指定日志格式函数的Logger中间件
func LoggerWithWriter(out io.Writer, notlogged …string) HandlerFunc:返回一个日志输出的中间件
func LoggerWithConfig(conf LoggerConfig) HandlerFunc:一个带有config的Logger中间件
func Recovery() HandlerFunc :返回一个从任何恐慌中恢复的中间件,如果有的话,写入500。
func WrapF(f http.HandlerFunc) HandlerFunc 将http.HandlerFunc类型包装为handlerfunc
func WrapH(h http.Handler) HandlerFunc 将http.Handler包装为handlerfunc

type LogFormatter

  1. type LogFormatter func(params LogFormatterParams) string

type LogFormatterParams

  1. type LogFormatterParams struct {
  2. Request *http.Request
  3. TimeStamp time.Time
  4. StatusCode int
  5. // Latency is how much time the server cost to process a certain request.
  6. Latency time.Duration
  7. // ClientIP equals Context's ClientIP method.
  8. ClientIP string
  9. // Method is the HTTP method given to the request.
  10. Method string
  11. // Path is a path the client requests.
  12. Path string
  13. // ErrorMessage is set if error has occurred in processing the request.
  14. ErrorMessage string
  15. // BodySize is the size of the Response Body
  16. BodySize int
  17. // Keys are the keys set on the request's context.
  18. Keys map[string]interface{}
  19. // contains filtered or unexported fields
  20. }

func (p *LogFormatterParams) IsOutputColor() bool :是否可以将颜色输出到日志

type LoggerConfig

  1. type LoggerConfig struct {
  2. // Optional. Default value is gin.defaultLogFormatter
  3. Formatter LogFormatter
  4. // Output is a writer where logs are written.
  5. // Optional. Default value is gin.DefaultWriter.
  6. Output io.Writer
  7. // SkipPaths is a url path array which logs are not written.
  8. // Optional.
  9. SkipPaths []string
  10. }

type ResponseWriter

  1. type ResponseWriter interface {
  2. http.ResponseWriter
  3. http.Hijacker
  4. http.Flusher
  5. http.CloseNotifier
  6. // Returns the HTTP response status code of the current request.
  7. Status() int
  8. // Returns the number of bytes already written into the response http body.
  9. // See Written()
  10. Size() int
  11. // Writes the string into the response body.
  12. WriteString(string) (int, error)
  13. // Returns true if the response body was already written.
  14. Written() bool
  15. // Forces to write the http header (status code + headers).
  16. WriteHeaderNow()
  17. // get the http.Pusher for server push
  18. Pusher() http.Pusher
  19. }

type Context

  1. type Context struct {
  2. Request *http.Request
  3. Writer ResponseWriter
  4. Params Params
  5. Keys map[string]interface{}
  6. Errors errorMsgs
  7. Accepted []string
  8. }

func (c *Context) ClientIP() string

  • 用户真实ip,它解析X-Real-IP和x - forward - for,以便与反向代理(如us: nginx或haproxy)正常工作

func (c Context) ContentType() string:返回请求的Content-Type标头
func (c
Context) Cookie(name string) (string, error):找一个cookie
func (c Context) IsWebsocket() bool 如果请求标头表明客户端正在发起websocket握手,返回true
func (c
Context) Copy() Context:Copy返回当前上下文的副本,该副本可以在请求范围之外安全地使用
func (c
Context) IsWebsocket() bool:如果请求头指示客户端正在发起websocket握手,则IsWebsocket返回true
func (c *Context) FullPath() string:返回被匹配的路径

  1. router.GET("/user/:id", func(c *gin.Context) {
  2. c.FullPath() == "/user/:id" // true
  3. })

错误终止
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) IsAborted() bool:如果当前上下文被中止,则IsAborted返回true

获取参数
func (c Context) Query(key string) string:获取get的k-v格式的参数
func (c
Context) DefaultQuery(key, defaultValue string) string:同上,不过可以设置默认值
func (c Context) Param(key string) string:获取get的路径参数
func (c
Context) PostForm(key string) string:获取post的参数
func (c Context) DefaultPostForm(key, defaultValue string) string:同上,不过可以设置默认值
func (c
Context) FormFile(name string) (multipart.FileHeader, error):获取一个文件
func (c
Context) MultipartForm() (multipart.Form, error):经过解析的多部分表单,包括文件上传
func (c
Context) SaveUploadedFile(file multipart.FileHeader, dst string) error :保存上传的文件
func (c
Context) GetHeader(key string) string : 获取请求体中的信息

*
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)

  1. GET /?name=Manu&lastname=
  2. ("Manu", true) == c.GetQuery("name")
  3. ("", false) == c.GetQuery("id")
  4. ("", true) == c.GetQuery("lastname")

参数绑定
func (c *Context) ShouldBind(obj interface{}) error

  • ShouldBind检查内容类型,自动选择绑定引擎,根据“内容类型”头部使用不同的绑定
  • “application/json” —> JSON binding
  • “application/xml” —> XML binding

func (c Context) ShouldBindJSON(obj interface{}) error
func (c
Context) ShouldBindQuery(obj interface{}) error
func (c Context) ShouldBindUri(obj interface{}) error
func (c
Context) ShouldBindHeader(obj interface{}) error
func (c Context) ShouldBindXML(obj interface{}) error
func (c
Context) ShouldBindYAML(obj interface{}) error
func (c *Context) ShouldBindWith(obj interface{}, b binding.Binding) error

响应
func (c Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)
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) HTML(code int, name string, obj interface{})
func (c
Context) JSON(code int, obj interface{})
func (c Context) SecureJSON(code int, obj interface{})
func (c
Context) JSONP(code int, obj interface{})
func (c Context) String(code int, format string, values …interface{})
func (c
Context) XML(code int, obj interface{})
func (c Context) YAML(code int, obj interface{})
func (c
Context) Status(code int)
func (c Context) Header(key, value string) 设置一个响应头
func (c
Context) Redirect(code int, location string) 重定向location 可以是relativePath
func (c *Context) Render(code int, r render.Render) 写响应头并调用Render,一般用上面的就够了

上下文参数传递
func (c Context) Set(key string, value interface{})
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) GetInt(key string) (i int)
func (c Context) GetInt64(key string) (i64 int64)
func (c
Context) GetString(key string) (s string)
func (c Context) GetStringMap(key string) (sm map[string]interface{})
func (c
Context) GetStringMapString(key string) (sms map[string]string)
func (c Context) GetStringMapStringSlice(key string) (smss map[string][]string)
func (c
Context) GetStringSlice(key string) (ss []string)
func (c Context) GetTime(key string) (t time.Time)
func (c
Context) Next():应该只在中间键中使用,意思是挂起当前的程序,继续执行其他中间键,在未来会被继续调用

SecureJSON类型

  1. func main() {
  2. r := gin.Default()
  3. // You can also use your own secure json prefix
  4. // r.SecureJsonPrefix(")]}',\n")
  5. r.GET("/someJSON", func(c *gin.Context) {
  6. names := []string{"lena", "austin", "foo"}
  7. // Will output : while(1);["lena","austin","foo"]
  8. c.SecureJSON(http.StatusOK, names)
  9. })
  10. // Listen and serve on 0.0.0.0:8080
  11. r.Run(":8080")
  12. }

JSONP类型

  1. func main() {
  2. r := gin.Default()
  3. r.GET("/JSONP", func(c *gin.Context) {
  4. data := gin.H{
  5. "foo": "bar",
  6. }
  7. //callback is x
  8. // Will output : x({\"foo\":\"bar\"})
  9. c.JSONP(http.StatusOK, data)
  10. })
  11. // Listen and serve on 0.0.0.0:8080
  12. r.Run(":8080")
  13. // client
  14. // curl http://127.0.0.1:8080/JSONP?callback=x
  15. }

测试目的

func CreateTestContext(w http.ResponseWriter) (c Context, r Engine): 为测试目的返回一个新的引擎和上下文

  1. func TestxxxHandle(t *testing.T) {
  2. ctx := tc.mockFn()
  3. handler := TestxxxHandle(ctx)
  4. w := httptest.NewRecorder()
  5. c, _ := gin.CreateTestContext(w)
  6. data, err := json.Marshal(tc.payload)
  7. assert.Nil(t, err, "marshaling request body")
  8. c.Request = &http.Request{
  9. Method: http.MethodPost,
  10. Body: io.NopCloser(bytes.NewBuffer(data)),
  11. }
  12. handler(c)
  13. assert.Equal(t, tc.statusCode, w.Code, "checking HTTP status code")
  14. }

func (engine Engine) ServeHTTP(w http.ResponseWriter, req http.Request) :处理http请求 [demo]。