一 、gin 入门
1. 安装gin :下载并安装 gin包:
$ go get -u github.com/gin-gonic/gin
2. 将 gin 引入到代码中:
import "github.com/gin-gonic/gin"
3.初始化项目
go mod init gin
4.完整代码
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run()
}
5.启动项目
go run main.go # 运行 main.go 并且在浏览器中访问 0.0.0.0:8080/ping
6.效果图
二、基础知识
go get -u
参数介绍:
-d 只下载不安装
-f 只有在你包含了 -u 参数的时候才有效,不让 -u 去验证 import 中的每一个都已经获取了,这对于本地 fork 的包特别有用
-fix 在获取源码之后先运行 fix,然后再去做其他的事情
-t 同时也下载需要为运行测试所需要的包
-u 强制使用网络去更新包和它的依赖包
-v 显示执行的命
三、gin测试用例
AsciiJSON 生成具有转义的非 ASCII 字符的 ASCII-only JSON。
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r:=gin.Default()
r.GET("/someJson", func(c *gin.Context) {
data:=map[string]interface{}{
"lang":"go 语言",
"tag":"<br>",
}
c.AsciiJSON(http.StatusOK,data)
})
r.Run(":8081")
}
为什么 浏览器和 终端命令行curl打印出来的结果格式不一样?gin.AsciiJSON
答:编码问题
绑定HTML复选框
package main
import "github.com/gin-gonic/gin"
type myForm struct {
Colors []string `form:"colors[]"`
}
func formHandler(c *gin.Context) {
var fakeForm myForm
c.ShouldBind(&fakeForm)
c.JSON(200, gin.H{"color": fakeForm.Colors})
}
func innerHandler(c *gin.Context) {
c.HTML(200, "form.html", nil)
}
func main() {
r := gin.Default()
r.LoadHTMLGlob("views/*")
r.GET("/", innerHandler)
r.POST("/", formHandler)
r.Run(":8082")
}
views/form.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/" method="POST">
<p>Check some colors</p>
<label for="red">Red</label>
<input type="checkbox" name="colors[]" value="red" id="red">
<label for="green">Green</label>
<input type="checkbox" name="colors[]" value="green" id="green">
<label for="blue">Blue</label>
<input type="checkbox" name="colors[]" value="blue" id="blue">
<input type="submit">
</form>
</body>
</html>
绑定查询字符串或表单数据
package main
import (
"github.com/gin-gonic/gin"
"log"
"time"
)
//表单字符串
type PersonString struct {
Name string `form:"name"`
Address string `form:"address" `
Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`
}
//请求json格式
type PersonJson struct {
Name string `json:"name"`
Address string `json:"address"`
Birthday time.Time `json:"birthday" time_format:"2006-01-02" time_utc:"1"`
}
func startPage(c *gin.Context) {
var person PersonString
err := c.Bind(&person)
//ShouldBind 与 Bind 打印结果一样
//err:=c.ShouldBind(&person)
if err == nil {
log.Println(person.Name)
log.Println(person.Address)
log.Println(person.Birthday)
log.Println("Binding success...")
} else {
log.Println("Binding failed...")
log.Println(err)
}
var personJson PersonJson
errJson := c.BindJSON(&personJson)
if errJson == nil {
log.Println(personJson.Name)
log.Println(personJson.Address)
//log.Println(personJson.Birthday)
log.Println("BindJson success...")
} else {
log.Println("BindJson failed...")
log.Println(errJson)
}
c.String(200, "success")
}
func main() {
log.Println("Hello World")
route := gin.Default()
route.GET("/testing", startPage)
route.Run(":8083")
}
请求:
string:
curl -X GET "http://0.0.0.0:8083/testing?name=appleboy&address=xyz&birthday=2023-03-15"
打印:结果
success
josn:
curl -X GET "http://0.0.0.0:8083/testing" --data '{"name":"JJ", "address":"xyz"}' -H "Content-Type:application/json"
结果:success
效果图:
绑定uri
package main
import "github.com/gin-gonic/gin"
type Person struct {
ID string `uri:"id" building:"required,uuid"`
Name string `uri:"name" building:"required"`
}
func main() {
r := gin.Default()
r.GET("/:name/:id", func(c *gin.Context) {
var person Person
if err := c.ShouldBindUri(&person); err != nil {
c.JSON(400, gin.H{"msg": err})
return
}
c.JSON(200, gin.H{"name": person.Name, "uuid": person.ID})
})
r.Run(":8080")
}
控制log 高亮输出,默认开启高亮
//强制log 高亮
gin.ForceConsoleColor()
//关闭log高亮
//gin.DisableConsoleColor()
6.自定义http配置:(监听端口,读写时间,最大读写字节数)
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.String(200, "pong")
})
//两行作用一样,谁先执行谁生效
//r.Run(":8080")
//http.ListenAndServe(":8081",r)
s := &http.Server{
Addr: ":8084",
Handler: r, //实例句柄
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
s.ListenAndServe()
}
自定义log文件
参考:https://learnku.com/docs/gin-gonic/1.7/examples-bind-uri/11391