Gin 是一个 Go (Golang) 编写的轻量级 http web 框架,运行速度非常快,Github Strat 量已经超过了 50k。
一、 环境搭建
1.1 下载以及安装gin
Documentation | Gin Web Framework
1.2 golang热加载
fresh插件:
二、 Gin框架中的路由
2.1 路由概述
路由(Routing)是由一个 URI(或者叫路径)和一个特定的 HTTP 方法(GET、POST 等)
组成的,涉及到应用如何响应客户端对某个网站节点的访问。
RESTful API 是目前比较成熟的一套互联网应用程序的 API 设计理论,在 RESTful 架构中,每个网址代表一种资源,不同的请求方式表示执行不同的操作:
GET(SELECT) | 从服务器取出资源(一项或多项) |
POST(CREATE) | 在服务器新建一个资源 |
PUT(UPDATE) | 在服务器更新资源(客户端提供改变后的完整资源) |
DELETE(DELETE) | 从服务器删除资源 |
2.2 简单路由配置
(可以通过 postman 测试)或者http://localhost:8080/
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(200, "我是新闻页面 111") //返回200表示成功
})
r.POST("/add", func(c *gin.Context) {
c.String(200, "这是一个post——主要用于增加数据")
})
r.PUT("/edit", func(c *gin.Context) {
c.String(200, "这是一个put请求 主要用于编辑数据")
})
r.DELETE("/delete", func(c *gin.Context) {
c.String(200, "这是一个DELETE请求 主要用于删除数据")
})
//启动一个web服务
r.Run() //默认在0.0.0.0.8080 启动服务
//r.Run(":8000")
}
2.3 c.String() c.JSON() c.JSONP() c.XML()
2.3.1 String
r.GET("/", func(c *gin.Context) {
c.String(200, "值:%v", "首页")
})
2.3.2 JSON
//JSON可以是inteface{}接口
r.GET("/json1", func(c *gin.Context) {
c.JSON(200, map[string]interface{}{
//c.JSON(200, gin.H{ //gin.H是 map[string]interface{}的缩写
"success": true,
"msg": "你好gin",
})
})
//JSON也可以是结构体
r.GET("/json3", func(c *gin.Context) {
a := &Article{
Title: "我是一个标题",
Desc: "描述",
Content: "测试内容",
}
c.JSON(http.StatusOK, a)
})
2.3.3 JSONP
和JSON写法一样,但是 输入:http://localhost:8080/jsonp?callback=xxxx
会生成前面带xxxx的格式:xxxx({"title":"我是一个标题-jsonp","desc":"描述","content":"测试内容"});
r.GET("/jsonp", func(c *gin.Context) {
a := &Article{
Title: "Jsonp",
Desc: "描述",
Content: "测试内容",
}
c.JSONP(200, a)
})
2.3.4 XML
用法同json,可以用结构体
r.GET("xml", func(c *gin.Context) {
c.XML(200, gin.H{
"success": true,
"msg": "你好gin 我是一个xml",
})
})
2.4 HTML 模板渲染
2.4.1 配置方法
主文件:
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
//配置模版文件
r.LoadHTMLGlob("/home/wolf/go_gin/gindmeo03/templates/**/*")
//两个*代表目录 相对路径不好用就用绝对路径
//HTML请求
r.GET("/html2", func(c *gin.Context) {
c.HTML(http.StatusOK, "default/index.html", gin.H{
"title": "这是一个商品页面",
"price": 20,
})
})
r.Run()
}
HTML文件:
<!--相当于给,模版定义一个名字 define end 成对出现-->
{{ define "default/index.html" }}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
{{template "public/page_header.html" .}} <!--嵌套 template 嵌套一个公共的模版-->
<h2>{{.title}}</h2>
<br>
{{.price}}
<br>
<h5>html的数据</h5>
{{template "public/page_footer.html" .}}
</body>
</html>
{{ end }}
2.4.2 HTML模版的基本语法
1、{{.}} 输出数据
模板语法都包含在{{和}}中间,其中{{.}}中的点表示当前对象。
<h3>{{.title}}</h3>
2. 变量
<h4>{{$obj := .title}}</h4>
<h4>{{$obj}}</h4>
3. 比较函数 条件判断
① 布尔函数会将任何类型的零值视为假,其余视为真。
② 下面是定义为函数的二元比较运算的集合:
eq 如果 arg1 == arg2 则返回真
ne 如果 arg1 != arg2 则返回真
lt 如果 arg1 < arg2 则返回真
le 如果 arg1 <= arg2 则返回真
gt 如果 arg1 > arg2 则返回真
ge 如果 arg1 >= arg2 则返回真
③ if用法:(注意结尾有{{end}})
{{if gt .score 90}}
<p>优秀</p>
{{else if gt .score 80}}
<p>良好</p>
{{else if gt .score 60}}
<p>及格</p>
{{else}}
<p>不及格</p>
{{end}}
4. range 遍历
① hobby是切片
"hobby": []string{"吃饭", "睡觉", "写代码"},
<ul>
{{range $key,$value:=.hobby}}
<li>{{$key}}--------{{$value}}</li>
{{end}}
</ul>
② newsList 是空接口嵌套的结构体
"newsList": []interface{}{
&Article{
Title: "新闻标题111",
Content: "新闻详情111",
},
&Article{
Title: "新闻标题222",
Content: "新闻详情222",
},
},
<ul>
{{range $key,$value:=.newsList}}
<li>{{$key}}--------{{$value.Title}}--------{{$value.Content}}</li>
{{end}}
</ul>
5. with 解构结构体
例:.代替了.news-->
"news": &Article{
Title: "新闻标题",
Content: "新闻内容",
},
<p>{{.news.Title}}</p>
<p>{{.news.Content}}</p>
//下面输出结果一致
<br>
{{with .news}}
<p>{{.Title}}</p>
<p>{{.Content}}</p>
{{end}}
6. 预定义函数 (了解)
预定义的全局函数如下:
{{len .title}}
7. 自定义模板函数
r.SetFuncMap(template.FuncMap{ 名字 值 }
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"html/template"
"time"
)
// 时间戳转换成日期
func UnixTotime(timestamp int) string {
fmt.Println(timestamp)
t := time.Unix(int64(timestamp), 0)
return t.Format("2006-01-02 15:04:05") //注意样式时间
}
// 例子2
func Println(str1 string, str2 string) string {
fmt.Println(str1, str2)
return str1 + "----------" + str2
}
func main() {
// 创建一个默认的路由引擎
r := gin.Default()
//自定义模版函数 要把这个函数放在加载模版欠
r.SetFuncMap(template.FuncMap{ //需要这样写
"UnixToTime": UnixTotime, //名字 值
"Println": Println,
})
//加载模板 放在配置路由上面
r.LoadHTMLGlob("/home/wolf/go_gin/gindmeo03/templates/**/*") //两个*代表目录
r.GET("/", func(c *gin.Context) {
c.HTML(200, "default/index.html", gin.H{
"title": "首页",
"msg": "我是msg",
"date": 1710491056,
})
})
r.Run()
}
<!--自定义模版函数名 要传入的参数-->
<br>
<br>
{{UnixToTime .date}}
<br>
<br>
{{Println .title .msg}}<!--函数 传入的参数-->
<!--注意需要两个br-->
2.5 静态文件服务
当我们渲染的 HTML 文件中引用了静态文件时,我们需要配置静态 web 服务
(static/css/bace.css)
文档目录
主文件
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"html/template"
)
func main() {
// 创建一个默认的路由引擎
r := gin.Default()
//自定义模版函数 要把这个函数放在加载模版欠
//r.SetFuncMap(template.FuncMap
// "UnixToTime": UnixTotime,
//加载模板 放在配置路由上面
r.LoadHTMLGlob("/home/wolf/go_gin/gindmeo03/templates/**/*") //两个*代表目录
//配置静态web目录 第一个参数表示路由,第二个参数表示映射的目录
r.Static("/static", "./static")
r.GET("/", func(c *gin.Context) {
c.HTML(200, "default/index.html", gin.H{
"title": "首页",
})
})
r.Run()
}
HTML文件
<!--相当于给,模版定义一个名字 define end 成对出现-->
{{ define "default/index.html" }}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<!--链接到静态文件-->
<link rel="stylesheet" href="/static/css/base.css">
</head>
<body>
{{template "public/page_header.html" .}}
<!--加载图片(需要先把图片复制到images的目录下才能用)-->
<img src="/static/images/IMG.jpg" style="max-width:10%" alt="">
<!--略去内容-->
</body>
</html>
{{ end }}
CSS静态文件
h1{
background: #000;
color: #fff;
text-align: center;
}
h2{
color: red;
}