Post

Gin

Gin

Gin基础

环境依赖

  • 环境配置查看 —— go env
  • 项目初始化 —— go mod init [项目名称/根目录名称]
  • 安装包 —— go get -u github.com/gin-gonic/gin
  • 运行 —— go run .\main.go

常用包

  • 热加载 fresh
    • github.com/gravityblast/fresh
  • http常量 例如 http.statusOK
    • import "net/http

默认路由+基础Restful接口

  • 默认路由 —— gin.Default()
  • 启动路由 —— r.Run(":8210") 默认端口 8080

基础Restful接口

每个网址代表一种资源, 不同的请求代表不同操作(增删改查) 请求(路由, 回调函数)

  • GET
  • POST
  • PUT
  • DELETE

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
func main() {
	// 创建一个默认的路由引擎
	r := gin.Default()
	//配置路由
	r.GET("/", func(c *gin.Context) {
		c.String(http.StatusOK, "值:%v", "你好gin")
	})
	r.GET("/news", func(c *gin.Context) {
		c.String(http.StatusOK, "我是新闻页面 111")
	})

	r.POST("/add", func(c *gin.Context) {
		c.String(http.StatusOK, "这是一个post--主要用于增加数据")
	})

	r.PUT("/edit", func(c *gin.Context) {
		c.String(200, "这是一个put请求 主要用于编辑数据")
	})

	r.DELETE("/delete", func(c *gin.Context) {
		c.String(200, "这是一个DELETE请求 用于删除数据")
	})
	// r.Run()  启动 HTTP 服务,默认在 0.0.0.0:8080 启动服务

	r.Run(":8000") //启动一个web服务

}

路由响应数据

  • c.String
    • 格式化输出 (code int, format string, value ...interface{})
  • c.JSON
    • map[string]interface{}{键值对}
    • gin.H{键值对}
    • 二者等价
    • 结构体对象 (默认返回结构体属性名,用 json 指定字段名称)
    • 返回内容:{json}
  • c.JSONP
    • 与JSON的区别在于 解决前端的跨域问题
    • 方法:访问 http://url/path?callback=xxx callback为固定的
    • 返回内容: xxx({json})
  • c.XML
    • 与JSON的区别在于 返回的数据格式为 XML 格式
  • c.HTML
    • 渲染模板前需要加载模板
      • router.LoadHTML(templates/*)
      • router.LoadHTMLFiles(“templates/1.html”, “templates/2.html”)
      • 二选一即可,代码在路由使用前加载,路径为相对路径
    • 参数 (状态码, "模板文件名称", 传入后台数据(与json格式相同))
    • 模板绑定后台值 {{.属性名}} (写在模板文件中)

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
type Article struct {
	Title   string `json:"title"`
	Desc    string `json:"desc"`
	Content string `json:"content"`
}

func main() {
	r := gin.Default()
	//配置模板的文件
	r.LoadHTMLGlob("templates/*")

	r.GET("/", func(c *gin.Context) {
		c.String(200, "值:%v", "首页")
	})
	r.GET("/json1", func(c *gin.Context) {
		c.JSON(200, map[string]interface{}{
			"success": true,
			"msg":     "你好gin",
		})
	})

	r.GET("/json2", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"success": true,
			"msg":     "你好gin--22",
		})
	})

	r.GET("/json3", func(c *gin.Context) {

		a := &Article{
			Title:   "我是一个标题",
			Desc:    "描述",
			Content: "测试内容",
		}
		c.JSON(200, a)
	})

	//响应Jsonp请求
	// http://localhost:8080/jsonp?callback=xxxx
	// xxxx({"title":"我是一个标题-jsonp","desc":"描述","content":"测试内容"});
	r.GET("/jsonp", func(c *gin.Context) {

		a := &Article{
			Title:   "我是一个标题-jsonp",
			Desc:    "描述",
			Content: "测试内容",
		}
		c.JSONP(200, a)
	})

	r.GET("/xml", func(c *gin.Context) {
		c.XML(http.StatusOK, gin.H{
			"success": true,
			"msg":     "你好gin 我是一个xml",
		})
	})

	r.GET("/news", func(c *gin.Context) {
		//r.LoadHTMLGlob("templates/*")
		c.HTML(http.StatusOK, "news.html", gin.H{
			"title": "我是后台的数据",
		})
	})

	r.GET("/goods", func(c *gin.Context) {
		c.HTML(http.StatusOK, "goods.html", gin.H{
			"title": "我是商品页面",
			"price": 20,
		})
	})

	r.Run()
}

HTML模板渲染

基础使用

  1. 加载模板
    1
    2
    3
    4
    5
    6
    7
    8
    
    // 目录结构
    // - project
    //     - main.go
    //     - templates
    //         - 一级目录
    // ** 代表一级目录, **/**/* 多级目录以此类推
    r.LoadHTMLGlob("templates/**/*")
    // r.LoadHTMLFiles("templates/1.html", "templates/2.html") —————— 需要指定具体文件名称
    
  1. 命名模板 ```html {{ define “default/index.html” }} <!DOCTYPE html>
Document

{{.title}}

{{ end }}

1
2
3
4
5
6
7
8
9
{: file='templates/default/index.html'}
3. 使用模板
```go
r.GET("/", func(c *gin.Context){
    // default/index.html 对应具体的模板名称
    c.HTML(http.StatusOK, "default/index.html", gin.H{   
        "title": "首页",
    })
})

基础语法

  • 变量
    • {{.}} —— 传入变量
    • $ —— 模板变量 <h4>{{$obj := .title}}</h4>
  • 移除空格 —— {{- .Name -}}
  • 比较函数
  • 条件判断
  • 遍历
  • 结构体命名空间

比较函数
  • eq —— 等于
  • ne —— 不等于
  • lt —— 小于
  • le —— 小于等于
  • gt —— 大于
  • ge —— 大于等于
条件判断 if
  1. if end
  2. if esle end
  3. if esle if end
  4. if <比较函数> <参数1> <参数2>

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{{if pipeline}} T1 {{end}}
{{if pipeline}} T1 {{else}} T0 {{end}}
{{if pipeline}} T1 {{else if pipeline}} T0 {{end}}
{{if gt .score 60}}
及格
{{else}}
不及格
{{end}}

{{if gt .score 90}}
优秀
{{else if gt .score 60}}
及格
{{else}}
不及格
{{end}}
遍历 range
  1. 遍历
  2. 遍历 else —— 当遍历对象为空时,执行 else 语句

  3. 语法:{{range $key, $value := .obj}} {{$key}} - {{$value}} {{end}}
  4. 语法:{{range $key, $value := .obj}} {{$key}} - {{$value}} {{else}} content {{end}}
命名空间 with
  • 有结构体
    1
    2
    3
    4
    5
    6
    7
    
    user := UserInfo{
      Name:
      "张三",
      Gender: "男",
      Age:
      18,
    }
    
  • 进行路由
    1
    2
    3
    4
    5
    6
    
    router.GET("/", func(c *gin.Context) {
      c.HTML(http.StatusOK, "default/index.html", map[string]interface{}{
      "user":
      user,
      })
    })
    
  • 使用 with 进行数据输出 ```go {{with .user}}

姓名:{{.Name}}

性别:{{.user.Gender}}

年龄:{{.Age}}

{{end}} ```

This post is licensed under CC BY 4.0 by the author.