gin 使用笔记(一)基础

Fork Me On Github
zodream 编程技术 Go 2021年04月

关于路由

路由 ` 和/` 可以分开作为两个路由, 但是如果只有一个,就会把没注册的那个重定向到注册的那个

go
   
r := gin.Default()
r.GET("/home", Index)
r.GET("/home/", Abount)
123

这种方法时有效的

如果只注册一个

go
  
r := gin.Default()
r.GET("/home", Index)
12

浏览器访问 http://localhost/home/ 就会响应 301 并跳转到 http://localhost/home

路由分组

可以通过 ` ` 进行更精确的分组

go
      
r := gin.Default()
blog := r.Group("/blog")
blog.GET("", Index)
g := blog.Group("")
g.Use(middleware.CORS)
g.GET("/count", Count)
123456

中间件

gin.HandlerFunc 只能通过 c.Abort 进行中断,否则会继续执行下去

go
       
r := gin.Default()
r.Use(func(c *gin.Context) {
    if false {
        c.AbortWithStatusJSON(400, json.RenderFailure(err.Error()))
        return
    }
})
1234567

c.Next() 不是必须调用,如果需要对输出结果进行操作,这是才需要在内部调用

在中间件中传值

c.Keys["key"] = val

路由方法

c.ShouldBindQuery 可以绑定查询值到模型

c.Get() c.GetInt() c.GetString() 等是获取 c.Keys 注册的值

c.Query 获取查询的值

c.ShouldBind 是绑定post 提交的值到模型

c.PostForm 获取post的值

获取网址中匹配的值

go
    
r.GET("/user/:id", func(c *gin.Context) {
    // a GET request to /user/john
    id := c.Param("id") // id == "john"
})
1234

模板

go
    
r := gin.Default()
r.Static("/assets", configs.Config.Asset) // 指定资源文件的路径及文件夹
r.StaticFile("/favicon.ico", configs.Config.Favicon) // 指定网站图标
r.LoadHTMLGlob("templates/**/*")
1234

特别注意:

templates/**/* 会匹配 templates 文件夹下的子文件夹中的文件,但是只会注册文件名

例如

templates/blog/index.htmltemplates/auth/index.html

go
   
func Index(ctx *gin.Context) {
    ctx.HTML(200, "index.html", gin.H{})
}
123

ctx.HTML(200, "blog/index.html", gin.H{}) 这样是访问不到的,

ctx.HTML(200, "index.html", gin.H{}) 这样才能访问到,但是访问的是 templates/blog/index.html

如果要两个文件都生效,只能改文件名 templates/auth/auth_index.html

ctx.HTML(200, "auth_index.html", gin.H{})

点击查看全文
标签: gin
0 258 0
gin 使用ShouldBindQuery或者ShouldBind获取数据