gin框架的导入下载
go get -u github.com/gin-gonic/gin
gin框架的使用
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
// 创建一个默认的路由引擎
r := gin.Default()
// GET:请求方式;/hello:请求的路径
// 当客户端以GET方法请求/hello路径时,会执行后面的匿名函数
r.GET("/hello", func(c *gin.Context) {
// c.JSON:返回JSON格式的数据
c.JSON(200, gin.H{
"message": "Hello world!",
})
})
// 启动HTTP服务,默认在0.0.0.0:8080启动服务
r.Run(:9090)//在本地9090端口使用
}
渲染
posts/index.html
文件的内容如下:
{{define "posts/index.html"}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>posts/index</title>
</head>
<body>
{{.title}}
</body>
</html>
{{end}}
users/index.html
文件的内容如下:
{{define "users/index.html"}} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>users/index</title> </head> <body> {{.title}} </body> </html> {{end}}
Gin框架中使用LoadHTMLGlob()
或者LoadHTMLFiles()
方法进行HTML模板渲染。
func main() {
r := gin.Default()
r.LoadHTMLGlob("templates/**/*")
//r.LoadHTMLFiles("templates/posts/index.html", "templates/users/index.html")
r.GET("/posts/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "posts/index.html", gin.H{
"title": "posts/index",
})
})
r.GET("users/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "users/index.html", gin.H{
"title": "users/index",
})
})
r.Run(":8080")
}
自定义模板函数 safe
func main() {
router := gin.Default()
router.SetFuncMap(template.FuncMap{
"safe": func(str string) template.HTML{
return template.HTML(str)
},
})
router.LoadHTMLFiles("./index.tmpl")
router.GET("/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.tmpl", "<a href='https://liwenzhou.com'>李文周的博客</a>")
})
router.Run(":8080")
}
html中
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>修改模板引擎的标识符</title>
</head>
<body>
<div>{{ . | safe }}</div>
</body>
</html>
json渲染
func main() {
r := gin.Default()
// gin.H 是map[string]interface{}的缩写
r.GET("/someJSON", func(c *gin.Context) {
// 方式一:自己拼接JSON
c.JSON(http.StatusOK, gin.H{"message": "Hello world!"})
})
r.GET("/moreJSON", func(c *gin.Context) {
// 方法二:使用结构体
var msg struct {
Name string `json:"user"`
Message string
Age int
}
msg.Name = "小王子"
msg.Message = "Hello world!"
msg.Age = 18
c.JSON(http.StatusOK, msg)
})
r.Run(":8080")
}
获取参数query
三种方法
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.GET("/web", func(c *gin.Context) {
name := c.Query("name") //通过query获取庆中秋中携带的querystring参数
age := c.Query("age")
//name := c.DefaultQuery("query", "没查询到")//娶不到就用指定的默认值
//name, ok := c.GetQuery("query")//取不到返回自定义值
//if !ok {
// name = "somebody"
//}
c.JSON(http.StatusOK, gin.H{
"name": name,
"age": age,
})
})
r.Run("192.168.255.79:9090")
}
处理登录
前端页面以及细节
inde.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<form action="/login" method="post" novalidate autocomplete="off">
<div>
<label for="username">username</label>
<input type="text" name="username" id="username">
</div>
<div>
<label for="password">password</label>
<input type="password" name="password" id="password">
</div>
<div>
<input type="submit" value="登录">
</div>
</form>
</body>
</html>
因为form表单用了 post请求
所以点击登录按钮后会请求另一个界面
但是登陆的 type 要设置submit 不能设置button
login.htnl
用来显示登录后的页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<form action="/login" method="post" novalidate autocomplete="off">
<div>
<label for="username">username</label>
<input type="text" name="username" id="username">
</div>
<div>
<label for="password">password</label>
<input type="password" name="password" id="password">
</div>
<div>
<input type="submit" value="登录">
</div>
</form>
</body>
</html>
mian.go
func main() {
r := gin.Default()
r.LoadHTMLFiles("./index.html", "./login.html")
r.GET("/login", func(c *gin.Context) {
c.HTML(http.StatusOK, "login.html", nil)
//login post
r.POST("/login", func(c *gin.Context) {
//第一种
//username := c.PostForm("username")
//password := c.PostForm("password")
//第二种
//username := c.DefaultPostForm("username", "somebody")
//password := c.DefaultPostForm("password", "***")
//第三种
password, ok := c.GetPostForm("password")
if !ok {
password = "***"
}
username, ok := c.GetPostForm("username")
if !ok {
username = "sb"
}
c.HTML(http.StatusOK, "index.html", gin.H{
"Name": username,
"Pass": password,
})
})
})
//
r.Run(":9090")
重定向
第一种方法指定访问到某网页
c.Redirect(http.StatusOK, "https://sougou.com/")
第二种指定函数内的某个路径
c.Request.URL.Path = "/b" r.HandleContext(c)
func main() {
r := gin.Default()
r.GET("/index", func(c *gin.Context) {
//c.JSON(http.StatusOK, gin.H{
// "status": "ok",
//})
c.Redirect(http.StatusOK, "https://sougou.com/")
})
r.GET("/a", func(c *gin.Context) {
//打开/a指向b
c.Request.URL.Path = "/b"
r.HandleContext(c)
})
r.GET("/b", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"name": "b",
})
})
r.Run(":9090")
}
路由
一般我们的请求方式又跟多
比如 get post delete put 等
r := gin.Default()
//get一般为查看信息方法·
r.GET("/index", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"method": "GET",
})
})
//delete一般为删除操作
r.DELETE("/index", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"method": "dellce",
})
})
//post一般为添加操作
r.POST("/index", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"method": "post",
})
})
//put一般为更新方法
r.PUT("/index", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"method": "put",
})
})
但是 any集合了所有常见的请求方法
//any能处理常见的所有请求方法 r.Any("/user", func(c *gin.Context) { switch c.Request.Method { case "GET": c.JSON(http.StatusOK, gin.H{"methos": "get"}) case "POST": c.JSON(http.StatusOK, gin.H{"method": "post"}) //... } })
noroute 则是 当用户输入一个没有的界面时 返回xxx 告诉用户没有这个界面
//noroute 没有这个界面时 自定义返回默认界面
r.NoRoute(func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"qimi": "qimi"})
})
路由组
Group
//路由组
videoGroup := r.Group("/video")
//{}分组 好区分这是一个路由组
{
videoGroup.GET("/index", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"meg": "/vidoe/index"})
})
videoGroup.GET("/xx", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"meg": "/vidoe/index"})
})
videoGroup.GET("/oo", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"meg": "/vidoe/index"})
})
}
当我们有二级菜单时 就要用到路由组 当然 路由组 用{} 包起来 看着更清晰 效果更好
中间件
用来验证登录 如果验证成功 则进入某网页 验证失败 则 返回登陆界面
func indexhandlFunc(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"mes": "index",
})
}
func m1(c *gin.Context) {
fmt.Println("m1...")
//计时
c.Next() //调用中间件后续的函数
//c.Abort() //阻止调用后续的函数
fmt.Println("m1 out")
}
func m2(c *gin.Context) {
fmt.Println("m2...")
//计时
c.Next() //调用中间件后续的函数
//c.Abort() //阻止调用后续的函数
fmt.Println("m2 out")
}
func m3(c *gin.Context) {
fmt.Println("m3...")
//计时
c.Next() //调用中间件后续的函数
//c.Abort() //阻止调用后续的函数
fmt.Println("m3 out")
}
func main() {
r := gin.Default()
r.Use(m1, m2)
r.GET("/index", m3, indexhandlFunc)
r.GET("/user", indexhandlFunc)
r.Run(":9090")
}
不插入c.next的话 服务端输出m1后就会输出m1out
插入的话走到c.next就会走下一个 函数
下一个函数走完 结束时会返回这个c.next
c.abort则阻止调用中间件后面的函数
r.User=()
全局注册中间件
gin.default 和gin.new
r := gin.Default() //默认使用Logger()和Recovery()中间件 分别是出错时返回日志 已经程序报错时 会跟终端返回500
//r := gin.New()//不想使用上面的两个中间件时 可以用gi.new()
校验中间件使用模板
func authMiddleware(doCheck bool) gin.HandlerFunc {
//连接数据库
//或一些其他准备工作
return func(c *gin.Context) {
if doCheck {
//业务逻辑
//登录校验
//if 是登陆用户
//c.Next()
//else
//c.Abort()
} else {
c.Next() //放行
}
}
}