Go Gin 框架学习笔记
Gin 描述
- 轻量级 http web 框架,允许速度非常快
- 最擅长的是 Api 接口的高并发
入门
-
创建默认的路由引擎
r = gin.Default()
-
启动 http 服务,默认在 8080 端口
r.Run(":8000")
-
返回字符串
c.String(200, "我是新闻页面") c.String(200, "值: %v", "你好gin")
-
gin 支持 RestFul
r.PUT() r.GET() r.POST() r.DELETE() r.UPDATE()
-
如果需要使用 http.StatusOK 之类的常量,需要引入 net/http 包
import "net/http"
-
路由函数
func (c *gin.Context) { }
或
func login(c *gin.Context) { ... } r.GET("/", login)
-
返回 json
c.JSON(200, map[string]interface{ } { "success": true, "msg": "你好gin", })
事实上在 gin 中
type H map[string]interface{ }
因此
c.JSON(200, gin.H { "success": true, "msg": "你好gin", })
从结构体中构造 json 并返回
type Article struct { Title string Desc string Context string } r.GET("/json", func (c *gin.Context) { a := &Article { Title: "我是标题" Desc: "我是描述" Context: "我是内容" } c.JSON(200, a) })
从结构体中构造 json 并返回时,给结构体字段取别名
type Article struct { Title string `json:"title"` Desc string `json:"desc"` Context string `json:"context"` }
解决跨域的 JSONP 请求
c.JSONP(200, a)
使用 JSONP 请求
http://localhost:8080/jsonp?callback=xxxx
返回 XML 数据
c.XML(http.StatusOK, gin.H { "success": true, "msg": "你好 gin" })
返回 html 数据
-
配置模板的文件
r.LoadHTMLGlob("templates/*")
-
news.html
<h2> { {.title}} </h2>
-
处理请求
c.HTML(http.StatusOK, "news.html", gin.H { "title": "我是后台的数据" })
-
HTML 模板渲染
-
从结构体中绑定数据
type Article struct { Title string Context string }
<h2> { {.title}} </h2> <p> { {.news.Title}} </p> <p> { {.news.Context}} </p>
r.GET("/news", func(c *gin.Context) { news := &Article { Title: "新闻标题", Context: "新闻详情", } c.HTML(http.StatusOK, "news.html", gin.H { "title": "新闻页面", "news": news, }) })
-
templates 目录下有一层子目录,其他情况依次递推
-
加载模板
r.LoadHTMLGlob("templates/**/*")
-
default/index.html 文件下取别名
<!-- 它们是成对出现的 --> { { define "default/news.html" }} <h2> { {.title}} </h2> { { end }}
-
处理请求
c.HTML(http.StatusOK, "default/news.html", gin.H { "title": "新闻页面" })
-
-
在 html 文件中定义变量
{ { $t := .title}} <p> { {.p}} </p>
-
比较函数,将零值视为假,其余视为真
二元比较符 描述 eq arg1 == arg2 则为真 ne arg1 != arg2 则为真 lt arg1 < arg2 则为真 le arg1 <= arg2 则为真 gt arg1 > arg2 则为真 ge arg1 >= arg2 则为真 使用
-
html 文件
{ { if ge .score 60 }} <p>及格</p> { { else }} <p>不及格</p> { { end }}
-
处理请求
c.HTML(200, "news.html", gin.H { "score": 89, })
-
-
循环遍历数据