准备工作
- 开启Go Module功能并生成go.mod文件
go mod init - Gin框架导包
go get -u github.com/gin-gonic/gin import "github.com/gin-gonic/gin"
基础用法
生成gin.Engine
gin.Default() 返回一个指向 gin.Engine 的指针,你可以通过它来配置和处理路由、中间件、请求和响应等。下面是入门程序,包括了生成 gin.Engine 和简单的路由配置
import (
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/user/info", func(c *gin.Context) {
c.String(200, "Hello World!")
})
err := r.Run(":8080")
if err != nil {
return
}
}
自定义拦截器
func main() {
r := gin.Default()
//传参方式url?userid=xxx&password=xxxxx 加了中间件
//myhandler()没有指定则全部一起用
r.GET("/user/info", myHandler(), func(context *gin.Context) {
//取出中间件值
usersession := context.MustGet("usersession").(string)
log.Println("--------------", usersession)
userid := context.Query("userid")
password := context.Query("password")
context.JSON(http.StatusOK, gin.H{"userid": userid,
"password": password})
})
err := r.Run(":8080")
if err != nil {
return
}
}
func myHandler() gin.HandlerFunc {
return func(context *gin.Context) {
context.Set("usersession", "userid-1")
context.Next()
context.Abort()
}
}
Restful Api
r.PUT("htllo", func(context *gin.Context) {
context.JSON(200, gin.H{"msg": "hello,world"})
})
r.DELETE("/htllo")
页面加载响应
//加载静态页面
r.LoadHTMLGlob("templates/*")
//响应一个页面给前端
r.GET("/index", func(context *gin.Context) {
context.HTML(http.StatusOK, "index.html", gin.H{"msg": "hello,world"})
})
传参方式url?userid=xxx&password=xxxxx
r.GET("/user/info", func(context *gin.Context) {
userid := context.Query("userid")
password := context.Query("password")
context.JSON(http.StatusOK, gin.H{"userid": userid,
"password": password})
})
传参方式user/info/1/kuangshen
r.GET("/user/info/:userid/:username", func(context *gin.Context) {
userid := context.Param("userid")
username := context.Param("username")
context.JSON(http.StatusOK, gin.H{"userid": userid, "username": username})
})
接收json
r.POST("/json", func(context *gin.Context) {
data, _ := context.GetRawData()
var m map[string]interface{}
_ = json.Unmarshal(data, &m)
context.JSON(http.StatusOK, m)
})
接收form表单
r.POST("/sdsd", func(context *gin.Context) {
username := context.PostForm("username")
password := context.PostForm("password")
context.JSON(http.StatusOK, gin.H{"username": username, "password": password})
})
重定向
r.GET("test", func(context *gin.Context) {
context.Redirect(http.StatusMovedPermanently, "https://www.baidu.com")
})
自定义404页面
把404.html放在静态文件目录下
r.NoRoute(func(context *gin.Context) {
context.HTML(http.StatusNotFound, "404.html", nil)
})
设置路由组
使用路由组可以帮助你更好地组织和管理路由,特别是在有大量相关路由的情况下。它也能够让你更容易地添加共享的中间件,以及在不同的路由组之间进行模块化。例如下面这个例子,所有在这个路由组中定义的路由都会以/user作为前缀。
userGroup := r.Group("/user")
{
userGroup.GET("/add")
userGroup.POST("/login")
userGroup.POST("/logout")
}
实战用法
以本次青训营大项目:极简版抖音后端为例,我们要实现的接口都是/douyin为前缀的,因此可以设置一个路由组,在路由组中进行接口的绑定。
具体来说,我们可以新建一个route层,在其中进行路由组的设置与路由的分发,还需要新建一个controller层,负责根据路由跳转执行对应的方法。这样一来,项目顶层的路由层、控制器层的基本架构就完成了,后续对controller层的相关代码进行补充即可。
项目目前的总览图:
入口方法:
路由层: