GIn框架简介
Gin是一个golang的微框架,基于 httprouter,封装比较优雅,API友好,源码注释比较明确。具有快速灵活,容错率高,高性能等特点。框架更像是一些常用函数或者工具的集合。借助框架开发,不仅可以省去很多常用的封装带来的时间,也有助于团队的编码风格和形成规范。
Gin 包括以下几个主要的部分:
设计精巧的路由/中间件系统; 简单好用的核心上下文 Context; 附赠工具集(JSON/XML 响应, 数据绑定与校验等)。 Gin 是一个 Golang 写的 web 框架,,它提供了类似martini但更好性能(路由性能约快40倍)的API服务。
先给出一个例子
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
// 1.创建路由
r := gin.Default()
// 2.绑定路由规则,执行的函数
// gin.Context,封装了request和response
r.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "hello World!")
})
// 3.监听端口,默认在8080
// Run("里面不指定端口号默认为8080")
r.Run(":8000")
}
Gin框架支持GET获取资源,POST新建资源,PUT更新资源,DELETE删除资源。
func main() {
r := gin.Default()
r.GET("/book", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "GET",
})
})
r.POST("/book", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "POST",
})
})
r.PUT("/book", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "PUT",
})
})
r.DELETE("/book", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "DELETE",
})
})
}
Gin加载静态资源
加载html页面等,LoadHTML全局加载函数
// 加载静态资源
r.LoadHTMLGlob("templates/*") // 全局加载
// 响应一个前端页面
r.GET("index", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", gin.H{
"msg": "后端传来的数据",
})
})
如果我们想引入CSS,js文件呢
// 1.创建路由
r := gin.Default()
// 加载静态资源
r.LoadHTMLGlob("templates/*") // 全局加载
// 加载资源文件
r.Static("/static", "./static")
// 响应一个前端页面
r.GET("index", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", gin.H{
"msg": "后端传来的数据",
})
})
gin获取参数
我们如何从路由中获取参数呢???
func main() {
// 1.创建路由
r := gin.Default()
// url?userid=111&username=xx
r.GET("/user/info", func(c *gin.Context) {
userid := c.Query("userid")
username := c.Query(`username`)
c.JSON(http.StatusOK, gin.H{
"userid": userid,
"username": username,
})
})
// url/:userid/:username
r.GET("/user/info/:userid/:username", func(c *gin.Context) {
userid := c.Param("userid")
username := c.Param(`username`)
c.JSON(http.StatusOK, gin.H{
"userid": userid,
"username": username,
})
})
r.Run(":8000")
}
前端给后端传数据
我们如何从前端拿到数据交给后端
// 前端给后端传JSON
r.POST("json", func(c *gin.Context) {
data, _ := c.GetRawData()
var m map[string]interface{}
_ = json.Unmarshal(data, &m) // 解析
c.JSON(http.StatusOK, m)
})
表单通过PostForm()接收
路由
重定向
当我们访问A路由时将自动重定向去B路由,举例如下
r.GET("/test", func(c *gin.Context) {
c.Redirect(http.StatusOK, "https://www.baidu.com")
})
路由组
这样我们就可以统一管理了,例如user的服务下面 /user/id 、/user/name 。。。更为直观方便。
userGroup:=r.Group("/user")
{
userGroup.GET("add")
userGroup.POST("login")
}