Gin简介
Gin是一个Golang写的微框架,它基于httprouter,封装得比较优雅,API友好,源码注释明确。Gin具有快速灵活、容错率高、高性能等特点,其路由性能比Martini大约快40倍。
Gin的路由系统设计精巧,基于httprouter,但在API友好性上更进一步。它提供了一种简单而强大的方式来定义和处理HTTP请求。
gin hello world
使用gin编写一个接口
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
router.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "Hello World")
})
router.Run(":8000")
}
router:=gin.Default():这是默认的服务器。使用gin的Default方法创建一个路由Handler;- 然后通过Http方法绑定路由规则和路由函数。不同于
net/http库的路由函数,gin进行了封装,把request和response都封装到了gin.Context的上下文环境中。 - 最后启动路由的Run方法监听端口。还可以用
http.ListenAndServe(":8080", router),或者自定义Http服务器配置。
两种启动方式
// 启动方式一
router.Run(":8000")
// 启动方式二
http.ListenAndServe(":8000", router)
修改IP为内网IP
router.Run("0.0.0.0:8000")
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func Index(context *gin.Context) {
context.String(200, "Hello Gin!")
}
func main() {
// 创建一个默认的路由
router := gin.Default()
// 绑定路由规则和路由函数,访问/index的路由,将由对应的函数去处理
router.GET("/index", Index)
// 启动监听,gin会把web服务运行在本机的0.0.0.0:8080端口上
router.Run("0.0.0.0:8080")
// 用原生http服务的方式, router.Run本质就是http.ListenAndServe的进一步封装
http.ListenAndServe(":8080", router)
}
状态码
200 表示正常响应 http.StatusOK
响应
返回字符串
router.GET("/txt", func(c *gin.Context) {
c.String(http.StatusOK, "返回txt")
})
返回Json
router.GET("/json", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
})
// 结构体转json
router.GET("/moreJSON", func(c *gin.Context) {
// You also can use a struct
type Msg struct {
Name string `json:"user"`
Message string
Number int
}
msg := Msg{"fengfeng", "hey", 21}
// 注意 msg.Name 变成了 "user" 字段
// 以下方式都会输出 : {"user": "hanru", "Message": "hey", "Number": 123}
c.JSON(http.StatusOK, msg)
})
返回xml
router.GET("/xml", func(c *gin.Context) {
c.XML(http.StatusOK, gin.H{"user": "hanru", "message": "hey", "status": http.StatusOK})
})
返回yaml
router.GET("/yaml", func(c *gin.Context) {
c.YAML(http.StatusOK, gin.H{"user": "hanru", "message": "hey", "status": http.StatusOK})
})
返回html
先要使用 LoadHTMLGlob()或者LoadHTMLFiles()方法来加载模板文件
//加载模板
router.LoadHTMLGlob("gin框架/templates/*")
//router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")
//定义路由
router.GET("/tem", func(c *gin.Context) {
//根据完整文件名渲染模板,并传递参数
c.HTML(http.StatusOK, "index.html", gin.H{
"title": "Main website",
})
})
在模板中使用这个title,需要使用{{ .title }}
不同文件夹下模板名字可以相同,此时需要 LoadHTMLGlob() 加载两层模板路径。
router.LoadHTMLGlob("templates/**/*")
router.GET("/posts/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
"title": "Posts",
})
c.HTML(http.StatusOK, "users/index.tmpl", gin.H{
"title": "Users",
})
})
总的来说,Gin是一个强大而灵活的web框架,适合用于构建高性能的web应用。使用Gin可以省去很多常用的封装带来的时间,有助于团队的编码风格和形成规范。