添加gin路由组

This commit is contained in:
朱毅骏 2021-07-20 18:38:00 +08:00
parent 15ed4ad55d
commit 652a4be113
13 changed files with 450 additions and 11 deletions

View File

@ -1,5 +1,5 @@
module studyGin/demo2
go 1.16
go 1.15
require github.com/gin-gonic/gin v1.7.2

View File

@ -4,24 +4,22 @@ import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
func main() {
r := gin.Default()
r.GET("/web", func(c *gin.Context) {
//获取请求参数
//name := c.Query("query")
//name := c.DefaultQuery("query","参数获取不到啦")
name,ok := c.GetQuery("query")
//name := c.DefaultQuery("query","somebody")
name, ok := c.GetQuery("query")
age := c.Query("age")
if !ok {
//取不到
name = "somebody"
}
c.JSON(http.StatusOK,gin.H{
"name":name,
"age":age,
c.JSON(http.StatusOK, gin.H{
"name": name,
"age": age,
})
})
r.Run(":8080")
r.Run(":9029")
}

82
demo3/main.go Normal file
View File

@ -0,0 +1,82 @@
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"log"
"net/http"
"time"
)
func indexHandler(c *gin.Context) {
fmt.Println("index ....")
name, ok := c.Get("name")
if !ok {
name = ""
}
time.Sleep(time.Millisecond * 10)
c.JSON(http.StatusOK, gin.H{
"msg": "index",
"name": name,
})
}
//定义中间件 统计耗时
func m1(c *gin.Context) {
log.Println("m1 in ....")
//计时
//调用后续的处理函数
start := time.Now()
c.Next()
//阻止调用后续函数
//c.Abort()
cost := time.Since(start)
log.Printf("cost:%v\n", cost)
log.Println("m1 out ....")
}
func m2(c *gin.Context) {
log.Println("m2 in ....")
//计时
//调用后续的处理函数
//c.Next()
c.Set("name", "zhuyijun")
//阻止调用后续函数
//c.Abort()
log.Println("m2 out ....")
}
func authMiddleware(doCheck bool) gin.HandlerFunc {
//连接数据库 。。。。
return func(c *gin.Context) {
if doCheck {
log.Println("开始判断是否登录")
//可以用于鉴权
_, ok := c.Get("name")
if !ok {
log.Println("没有登录")
c.Abort()
}
log.Println("已经登录成功")
c.Next()
} else {
c.Next()
}
}
}
func main() {
r := gin.Default()
r.Use(m1, m2)
r.GET("/", authMiddleware(false), indexHandler)
//第一种
shopGroup := r.Group("/shop", authMiddleware(true))
{
shopGroup.GET("/index", indexHandler)
}
//第二种
vedioGroup := r.Group("/vedio")
vedioGroup.Use(authMiddleware(true))
{
vedioGroup.GET("/index", indexHandler)
}
r.Run(":9029")
}

5
gindemo1/go.mod Normal file
View File

@ -0,0 +1,5 @@
module studyGin/gindemo1
go 1.15
require github.com/gin-gonic/gin v1.7.2

246
gindemo1/main.go Normal file
View File

@ -0,0 +1,246 @@
package main
import (
"log"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.LoadHTMLGlob("templates/*")
r.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "login.html", nil)
})
r.POST("/login", func(c *gin.Context) {
username, _ := c.GetPostForm("username")
password, _ := c.GetPostForm("password")
c.HTML(http.StatusOK, "success.html", gin.H{
"username": username,
"password": password,
})
})
r.GET("/param/:name/:age", func(c *gin.Context) {
name := c.Param("name")
age := c.Param("age")
c.HTML(http.StatusOK, "param.html", gin.H{
"name": name,
"age": age,
})
})
r.GET("/blog/:year/:month", func(c *gin.Context) {
year := c.Param("year")
month := c.Param("month")
c.HTML(http.StatusOK, "blog.html", gin.H{
"year": year,
"month": month,
})
})
type UserInfo struct {
Username string `form:"username" json:"username"`
Password string `form:"password" json:"password"`
}
r.GET("/user", func(c *gin.Context) {
//username := c.Query("username")
//password := c.Query("password")
//user := &UserInfo{
// Username: username,
// Password: password,
//}
user := &UserInfo{}
//将传入的参数和user的属性绑定起来
err := c.ShouldBind(&user)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"msg": "参数错误",
})
} else {
c.HTML(http.StatusOK, "user.html", gin.H{
"user": user,
})
}
})
r.POST("/form", func(c *gin.Context) {
user := &UserInfo{}
//将传入的参数和user的属性绑定起来
err := c.ShouldBind(&user)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"msg": "参数错误",
})
} else {
c.HTML(http.StatusOK, "user.html", gin.H{
"user": user,
})
}
})
r.GET("/upload", func(c *gin.Context) {
c.HTML(http.StatusOK, "upload.html", nil)
})
r.MaxMultipartMemory = 8 << 20 //8M内存限制
r.POST("/upload", func(c *gin.Context) {
//请求中读取文件
file, err := c.FormFile("file")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"msg": err.Error(),
})
} else {
//将文件保存到本地
c.SaveUploadedFile(file, "upload/"+file.Filename)
c.JSON(http.StatusOK, gin.H{
"status": "OK",
"url": "/upload",
})
}
})
r.POST("/uploads", func(c *gin.Context) {
//请求中读取文件
form, _ := c.MultipartForm()
files := form.File["file"]
for i, file := range files {
log.Println(i, file.Filename)
c.SaveUploadedFile(file, "upload/"+file.Filename)
}
c.JSON(http.StatusOK, gin.H{
"status": "OK",
"msg": "多文件上传成功",
})
})
//http重定向
r.GET("/test", func(c *gin.Context) {
//跳转
c.Redirect(http.StatusMovedPermanently, "https://www.bilibili.com")
})
//
r.GET("/a", func(c *gin.Context) {
//转跳到/b 对于的路由处理函数
//将请求URI修改
c.Request.URL.Path = "/b"
//继续后续处理
r.HandleContext(c)
})
r.GET("/b", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"status": "OK b",
})
})
//路由与路由组
r.GET("/index", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"method": "GET",
})
})
r.POST("/index", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"method": "POST",
})
})
r.PUT("/index", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"method": "PUT",
})
})
r.DELETE("/index", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"method": "DELETE",
})
})
//r.HEAD("/index", func(c *gin.Context) {
// c.JSON(http.StatusOK, gin.H{
// "method": "HEAD",
// })
//})
r.Any("/any", func(c *gin.Context) {
switch c.Request.Method {
case http.MethodGet:
c.JSON(http.StatusOK, gin.H{
"method": "GET",
})
case http.MethodPost:
c.JSON(http.StatusOK, gin.H{
"method": "POST",
})
case http.MethodPut:
c.JSON(http.StatusOK, gin.H{
"method": "PUT",
})
case http.MethodDelete:
c.JSON(http.StatusOK, gin.H{
"method": "DELETE",
})
case http.MethodHead:
c.JSON(http.StatusOK, gin.H{
"method": "HEAD",
})
case http.MethodPatch:
c.JSON(http.StatusOK, gin.H{
"method": "Patch",
})
}
})
//访问路由中不存在的转跳到404.html
r.NoRoute(func(c *gin.Context) {
c.HTML(http.StatusNotFound, "404.html", gin.H{})
})
//视频的首页和详情页
//r.GET("/video/index", func(c *gin.Context) {
// c.JSON(http.StatusOK, gin.H{
// "msg": "/video/index",
// })
//})
//r.GET("/video/main", func(c *gin.Context) {
// c.JSON(http.StatusOK, gin.H{
// "msg": "/video/main",
// })
//})
//商城的首页和详情页
//r.GET("/shop/index", func(c *gin.Context) {
// c.JSON(http.StatusOK, gin.H{
// "msg": "/shop/index",
// })
//})
//路由组
//将共用前缀提取出来
vedioGroup := r.Group("/video")
{
vedioGroup.GET("/index", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"msg": "/video/index",
})
})
vedioGroup.GET("/main", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"msg": "/video/main",
})
})
}
shopGroup := r.Group("/shop")
{
shopGroup.GET("/index", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"msg": "/shop/index",
})
})
shopGroup.GET("/main", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"msg": "/shop/main",
})
})
xx := shopGroup.Group("/xx")
xx.GET("/oo", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"msg": "/shop/xx/oo",
})
})
}
r.Run(":9029")
}

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>404 not found page</h1>
</body>
</html>

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{.year}} {{.month}}
</body>
</html>

View File

@ -0,0 +1,20 @@
<!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>Login</title>
</head>
<body>
<h1>登录页面</h1>
<form action="/login" method="post">
<label for="username">username:</label>
<input type="text" name="username" id="username"><br>
<label for="password">password:</label>
<input type="password" name="password" id="password"><br>
<input type="submit" value="login">
</form>
</body>
</html>

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{.name}} {{.age}}
</body>
</html>

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Hello {{.username}}</h1>
</body>
</html>

View File

@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传文件</title>
</head>
<body>
<h4>单文件上传</h4>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file"><br>
<input type="submit" value="上传">
</form>
<br>
<h4>多文件上传</h4>
<form action="/uploads" method="post" enctype="multipart/form-data">
<input type="file" name="file" multiple="true"><br>
<input type="submit" value="上传">
</form>
</body>
</html>

View File

@ -0,0 +1,11 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{.user.Username}}
{{.user.Password}}
</body>
</html>

17
ormDemo1/main.go Normal file
View File

@ -0,0 +1,17 @@
package main
import "github.com/jinzhu/gorm"
type UserInfo struct {
ID uint
Name string
Gender string
Hobby string
}
func init() {
gorm.Open("mysql", "root:123456@tcp(localhost:3306)/gin?charset=utf8&parseTime=True&loc=Local")
}
func main() {
}