gin框架学习笔记
gin官网
环境搭建
搭建golang开发环境
参考我的文章:https://editor.csdn.net/md/?articleId=119923552
创建GinLearn项目
mkdir GinLearn
cd GinLearn
go env -w GOPROXY=https://goproxy.cn,direct
mkdir api
mkdir assets
mkdir cmd
mkdir configs
mkdir internal
mkdir logs
mkdir pkg
mkdir tests
mkdir vendor
mkdir web
cd cmd
mkdir GinLearn
cd GinLearn
touch main.go
cd ../../
go mod init liuyunuo.cn/GinLearn
main.go
package main
import "fmt"
func main() {
fmt.Println("Hello World!")
}
vscode 配置启动脚本lanuch.json
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "GinLearn",
"type": "go",
"request": "launch",
"mode": "auto",
"cwd": "${workspaceFolder}",
"program": "${workspaceFolder}/cmd/GinLearn/main.go",
"env": {
"GOPATH": "/usr/local/go/bin/go",
"GOROOT": "/usr/local/go"
},
"args": [
"-c",
"config/config.yaml"
],
"internalConsoleOptions": "openOnFirstSessionStart"
}
]
}
F5运行,没有意外输出HelloWorld
GinLearn Hello World!
cd GinLearn
go get -u github.com/gin-gonic/gin
go mod vendor
修改main.go
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
func main() {
// 创建一个默认的路由引擎
r := gin.Default()
// 配置路由
r.GET("/", func(c *gin.Context) {
c.String(200, "GinLearn Hello World!\n")
})
// 启动HTTP服务
r.Run(":8000")
fmt.Println("Hello World!")
}
F5启动服务,测试一下
$ wget -q -O - http://192.168.1.41:8000/
GinLearn Hello World!
RESTful
GET
// GET
r.GET("/test", func(c *gin.Context) {
c.String(200, "GinLearn[GET] Hello World!\n")
})
测试
$ wget -q --method=GET -O - http://192.168.1.41:8000/test
GinLearn[GET] Hello World!
POST
// POST
r.POST("/test", func(c *gin.Context) {
c.String(200, "GinLearn[POST] Hello World!\n")
})
测试
$ wget -q --method=GET -O - http://192.168.1.41:8000/test
GinLearn[GET] Hello World!
$ wget -q --method=POST -O - http://192.168.1.41:8000/test
GinLearn[POST] Hello World!
PUT
// PUT
r.PUT("/test", func(c *gin.Context) {
c.String(200, "GinLearn[PUT] Hello World!\n")
})
测试
$ wget -q --method=PUT -O - http://192.168.1.41:8000/test
GinLearn[PUT] Hello World!
DELETE
// DELETE
r.DELETE("/test", func(c *gin.Context) {
c.String(200, "GinLearn[DELETE] Hello World!\n")
})
测试
$ wget -q --method=DELETE -O - http://192.168.1.41:8000/test
GinLearn[DELETE] Hello World!
响应数据
text/plain 响应
r.GET("/string", func(c *gin.Context) {
c.String(200, "STRING")
})
测试
$ wget -q -O - http://192.168.1.41:8000/string
STRING#
application/json 响应
定义一个样式,其中msg是必选的
type JsonResponse struct {
Ret bool `json:"ret"`
Msg string `json:"msg,omitempty"`
}
路由配置
r.GET("/json1", func(c *gin.Context) {
c.JSON(200, map[string]interface{}{
"ret": true,
"msg": "正确",
})
})
r.GET("/json2", func(c *gin.Context) {
c.JSON(200, gin.H{
"ret": false,
"msg": "错误",
})
})
r.GET("/json3", func(c *gin.Context) {
c.JSON(200, JsonResponse{
Ret: true,
Msg: "msg",
})
})
测试
$ wget -q -O - http://192.168.1.41:8000/json1
{"msg":"正确","ret":true}#
$ wget -q -O - http://192.168.1.41:8000/json2
{"msg":"错误","ret":false}#
$ wget -q -O - http://192.168.1.41:8000/json3
{"ret":true,"msg":"msg"}#
application/javascript 响应
路由配置
r.GET("/jsonp", func(c *gin.Context) {
c.JSONP(200, JsonResponse{
Ret: true,
Msg: "msg",
})
})
测试
$ wget -q -O - "http://192.168.1.41:8000/jsonp"
{"ret":true,"msg":"msg"}#
$ wget -q -O - "http://192.168.1.41:8000/jsonp?callback=JsonpCallback"
JsonpCallback({"ret":true,"msg":"msg"});#
application/xml 响应
定义一个样式,其中msg是必选的
type XmlResponse struct {
Ret bool `xml:"ret"`
Msg string `xml:"msg,omitempty"`
}
路由配置
r.GET("/xml1", func(c *gin.Context) {
c.XML(200, gin.H{
"ret": false,
"msg": "错误",
})
})
r.GET("/xml2", func(c *gin.Context) {
c.XML(200, XmlResponse{
Ret: true,
Msg: "msg",
})
})
测试
$ wget -q -O - http://192.168.1.41:8000/xml1
<map><msg>错误</msg><ret>false</ret></map>#
$ wget -q -O - http://192.168.1.41:8000/xml2
<XmlResponse><ret>true</ret><msg>msg</msg></XmlResponse>#
text/html 响应 (模板渲染)
加载html模板
r.LoadHTMLGlob("./web/templates/*")
模板
$ cat ./web/templates/HelloWorld.html
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<h2>Hello World!</h2>
<body>
</html>#
$ cat ./web/templates/HelloName.html
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<h2>{{.name}},你好</h2>
<body>
</html>#
路由配置
r.GET("/xml1", func(c *gin.Context) {
c.XML(200, gin.H{
"ret": false,
"msg": "错误",
})
})
r.GET("/xml2", func(c *gin.Context) {
c.XML(200, XmlResponse{
Ret: true,
Msg: "msg",
})
})
测试
$ wget -q -O - http://192.168.1.41:8000/html1
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<h2>Hello World!</h2>
<body>
</html>#
$ wget -q -O - http://192.168.1.41:8000/html2
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<h2>body,你好</h2>
<body>
</html>#
设置静态路由
r.Static("/static", "./web/static")
index.html
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<form action="/form" method="post">
姓名:<input type="text" name="name" /> <br>
年龄:<input type="text" name="age" /> <br>
<input type="submit" value="提交">
</form>
</body>
</html>
请求参数
query
路由设置
r.GET("/query", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"name": c.Query("name"),
"age": c.DefaultQuery("age", "18"),
})
})
测试
$ wget -q -O - "http://192.168.1.41:8000/query"
{"age":"18","name":""}#
$ wget -q -O - "http://192.168.1.41:8000/query?name=liuyuelong"
{"age":"18","name":"liuyuelong"}#
$ wget -q -O - "http://192.168.1.41:8000/query?name=DerekLiu&age=32"
{"age":"32","name":"DerekLiu"}#
form
路由
r.POST("/form", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"name": c.PostForm("name"),
"age": c.DefaultPostForm("age", "18"),
})
})
测试
$ wget -q -O - --header='Content-Type: application/x-www-form-urlencoded;charset=utf-8' --post-data="name=liuyelong&age=123" "http://192.168.1.41:8000/form"
{"age":"123","name":"liuyelong"}#
param
动态路由
r.GET("param/:name/:age", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"name": c.Param("name"),
"age": c.Param("age"),
})
})
测试
$ wget -q -O - "http://192.168.1.41:8000/param/liuyuelong/18"
{"age":"18","name":"liuyuelong"}#
json,xml
直接拿字符串,然后自己解析
路由分组
路由分组后添加路由
group := r.Group("/api")
group.GET("/", func(c *gin.Context) {
c.String(200, "GinLearn[API] Hello World!\n")
})
测试
$ wget -q -O - "http://192.168.1.41:8000/api"
GinLearn[API] Hello World!