Gin 是 Go语言写的一个 web 框架,它具有运行速度快,分组的路由器,良好的崩溃捕获和错误处理,非常好的支持中间件和 json。
特性
- 快速
基于 Radix 树的路由,小内存占用。没有反射。可预测的 API 性能。
- 支持中间件
传入的 HTTP 请求可以由一系列中间件和最终操作来处理。 例如:Logger,Authorization,GZIP,最终操作 DB。
- Crash 处理
Gin 可以 catch 一个发生在 HTTP 请求中的 panic 并 recover 它。这样,你的服务器将始终可用。例如,你可以向 Sentry 报告这个 panic!
- JSON 验证
Gin 可以解析并验证请求的 JSON,例如检查所需值的存在。
- 路由组
更好地组织路由。是否需要授权,不同的 API 版本…… 此外,这些组可以无限制地嵌套而不会降低性能。
- 错误管理
Gin 提供了一种方便的方法来收集 HTTP 请求期间发生的所有错误。最终,中间件可以将它们写入日志文件,数据库并通过网络发送。
- 内置渲染
Gin 为 JSON,XML 和 HTML 渲染提供了易于使用的 API。
- 可扩展性
GIN下载
go get -u github.com/gin-gonic/gin
GIN实例
package main
import (
"github.com/gin-gonic/gin"
)
func sayHello(c *gin.Context) {
// c.JSON:返回JSON格式的数据
c.JSON(200, gin.H{
"message": "Hello world!",
})
}
func main() {
// 创建一个默认的路由引擎
r := gin.Default()
// GET:请求方式;/hello:请求的路径
// 当客户端以GET方法请求/hello路径时,会执行后面的sayHello函数
r.GET("/hello", sayHello)
// 启动HTTP服务,默认在0.0.0.0:8080启动服务
r.Run()
}
RESTful API
REST与技术无关,代表的是一种软件架构风格,REST是Representational State Transfer的简称,中文翻译为“表征状态转移”或“表现层状态转化”。
GET用来获取资源POST用来新建资源PUT用来更新资源DELETE用来删除资源。
只要API程序遵循了REST风格,那就可以称其为RESTful API。目前在前后端分离的架构中,前后端基本都是通过RESTful API来进行交互。
案例
package main
import (
"encoding/json"
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
//创建一个服务
ginServer := gin.Default()
ginServer.Use()
//访问地址,处理我们的请求
//Gin Restful
//ginServer.GET("/hello", func(context *gin.Context) {
// context.JSON(200, gin.H{"msg": "hello,word"})
//})
//ginServer.POST("/user", func(context *gin.Context) {
// context.JSON(200, gin.H{"msg": "post,user"})
//})
//ginServer.GET("/user", func(context *gin.Context) {
// context.JSON(200, gin.H{"msg": "get,user"})
//})
//加载静态页面
ginServer.LoadHTMLGlob("template/*")
//加载资源文件
ginServer.Static("/static", "./static")
//响应一个页面给前端
ginServer.GET("/index", func(context *gin.Context) {
//context.JSON() json 数据
context.HTML(http.StatusOK, "index.html", gin.H{
"msg": "这是Go后台传递的数据",
})
})
//接收前端传递过来的参数
//url?userid=xxx&username=xxx(传统风格)
ginServer.GET("/user/info", func(context *gin.Context) {
userid := context.Query("userid")
username := context.Query("username")
context.JSON(http.StatusOK, gin.H{
"userid": userid,
"username": username,
})
})
// /user/info/1/rena(restful风格)
ginServer.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
ginServer.POST("/json", func(context *gin.Context) {
data, _ := context.GetRawData()
var m map[string]interface{}
//序列化包装为json数据
_ = json.Unmarshal(data, &m)
context.JSON(http.StatusOK, m)
})
//服务器端口
ginServer.Run(":8082")
}