在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Gin 基础 :Gin 的hello world :package main import ( "github.com/gin-gonic/gin" "net/http" ) func main() { engine := gin.Default() engine.GET("/", func(context *gin.Context) { context.String(http.StatusOK,"hello world!") }) engine.Run() }
Gin 的 context.Params(path 参数) :package main import ( "fmt" "github.com/gin-gonic/gin" "net/http" ) func main() { engine := gin.Default() engine.GET("/:name/*rest", func(context *gin.Context) { context.String(http.StatusOK,"hello world!") fmt.Println(context.Params) params := context.Params fmt.Printf("%T\n", params) ret,ok := params.Get("name") if ok{ fmt.Println(ret) } fmt.Println(params[0]) }) engine.Run() } Gin 的 context.Query (get 参数):package main import ( "fmt" "github.com/gin-gonic/gin" "net/http" ) func main() { engine := gin.Default() engine.GET("/", func(context *gin.Context) { context.String(http.StatusOK,"hello world!") fmt.Println(context.Query("name")) // 如果不存在返回 空串 fmt.Println(context.DefaultQuery("name","none"))// 如果不存在返回 none }) engine.Run() } Gin 的 context.PostForm(post 参数):package main import ( "fmt" "github.com/gin-gonic/gin" "net/http" ) func main() { engine := gin.Default() engine.POST("/", func(context *gin.Context) { context.String(http.StatusOK,"hello world") fmt.Println(context.PostForm("name")) fmt.Println(context.DefaultPostForm("name","none")) }) engine.Run() } Gin 的HTML渲染:package main import ( "github.com/gin-gonic/gin" "html/template" "net/http" ) func main() { eng := gin.Default() eng.SetFuncMap(template.FuncMap{ "safe": func(s string)template.HTML { return template.HTML(s) }, }) eng.LoadHTMLGlob("templates/**/*") eng.GET("/test01", func(context *gin.Context) { context.HTML(http.StatusOK,"test/test01.html",gin.H{ "a":`<a href="http://www.baidu.com">百度一下</a>`, }) }) eng.Run() } {{define "test/test01.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> <h3>hello test01</h3> {{ .a | safe }} </body> </html> {{end}} 注意:使用自定义模板函数的时候要先 SetFuncMap 后 LoadHTMLGlob
当HTML文件中引用了静态文件时: package main import ( "github.com/gin-gonic/gin" "html/template" "net/http" ) func main() { eng := gin.Default() eng.SetFuncMap(template.FuncMap{ "safe": func(s string)template.HTML { return template.HTML(s) }, }) eng.Static("/xxx","./static") eng.LoadHTMLGlob("templates/**/*") eng.GET("/test01", func(context *gin.Context) { context.HTML(http.StatusOK,"test/test01.html",gin.H{ "a":`<a href="http://www.baidu.com">百度一下</a>`, }) }) eng.Run() } {{define "test/test01.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> <h3>hello test01</h3> {{ .a | safe }} <script src="xxx/js/my.js"></script> <script> printHello() </script> </body> </html> {{end}} function printHello() {
console.log("hello world!")
}
Gin 的文件上传:单个文件上传: <!DOCTYPE html> <html lang="zh-CN"> <head> <title>上传文件示例</title> </head> <body> <form action="http://127.0.0.1:8080/upload" method="post" enctype="multipart/form-data"> <input type="file" name="f1"> <input type="submit" value="上传"> </form> </body> </html> package main import ( "fmt" "github.com/gin-gonic/gin" "log" "net/http" ) func main() { eng :=gin.Default() eng.POST("/upload", func(context *gin.Context) { file,err := context.FormFile("f1") if err != nil { context.JSON(http.StatusInternalServerError,gin.H{ "msg":err.Error(), }) } log.Println(file.Filename) dst := fmt.Sprintf("D:/temp/%s",file.Filename) context.SaveUploadedFile(file,dst) context.JSON(http.StatusOK,gin.H{ "msg":fmt.Sprintf(`%s uploaded!`,file.Filename), }) }) eng.Run() } 多个文件上传: package main import ( "fmt" "github.com/gin-gonic/gin" "log" "net/http" ) func main() { eng :=gin.Default() eng.POST("/upload", func(context *gin.Context) { // 多文件 form,_ := context.MultipartForm() files := form.File["f1"] for idx,file := range files{ log.Printf(file.Filename) dst := fmt.Sprintf("D:/temp/%s_%d",file.Filename,idx) context.SaveUploadedFile(file,dst) context.JSON(http.StatusOK,gin.H{ "msg":fmt.Sprintf(`%s uploaded!`,file.Filename), }) } }) eng.Run() } <!DOCTYPE html> <html lang="zh-CN"> <head> <title>上传文件示例</title> </head> <body> <form action="http://127.0.0.1:8080/upload" method="post" enctype="multipart/form-data"> <input type="file" name="f1" multiple> <input type="submit" value="上传"> </form> </body> </html>
Gin 的重定向:package main import ( "github.com/gin-gonic/gin" "net/http" ) func main() { eng :=gin.Default() eng.GET("/test", func(context *gin.Context) { context.Redirect(http.StatusMovedPermanently,"http://www.baidu.com") }) eng.Run() }
Gin 的请求的转发:package main import ( "github.com/gin-gonic/gin" "net/http" ) func main() { eng :=gin.Default() eng.GET("/a", func(context *gin.Context) { context.Request.URL.Path = "/b" eng.HandleContext(context) }) eng.GET("/b", func(context *gin.Context) { context.JSON(http.StatusOK,gin.H{ "msg":"ok2", }) }) eng.Run() }
Gin 的路由:context.Any() 可以接受任何方式的请求, context.NoRoute() 处理没有匹配的路由,404 请求, package main import ( "github.com/gin-gonic/gin" "net/http" ) func main() { eng :=gin.Default() eng.LoadHTMLGlob("templates/*") eng.NoRoute(func(context *gin.Context) { context.HTML(http.StatusNotFound,"404.html",nil) }) eng.Run() } 路由组: 习惯性一对 package main import ( "github.com/gin-gonic/gin" "net/http" ) func main() { eng :=gin.Default() eng.LoadHTMLGlob("templates/*") eng.NoRoute(func(context *gin.Context) { context.HTML(http.StatusNotFound,"404.html",nil) }) userGroup := eng.Group("/user") { userGroup.GET("/index", func(context *gin.Context) { context.JSON(http.StatusOK,gin.H{"msg":"user_index"}) }) userGroup.GET("/login", func(context *gin.Context) { context.JSON(http.StatusOK,gin.H{"msg":"user_login"}) }) } adminGroup := eng.Group("/admin") { adminGroup.GET("/index", func(context *gin.Context) { context.JSON(http.StatusOK,gin.H{"msg":"admin_index"}) }) adminGroup.GET("/login", func(context *gin.Context) { context.JSON(http.StatusOK,gin.H{"msg":"admin_login"}) }) } eng.Run() } 路由组也可以嵌套: package main import ( "github.com/gin-gonic/gin" "net/http" ) func main() { eng :=gin.Default() eng.LoadHTMLGlob("templates/*") eng.NoRoute(func(context *gin.Context) { context.HTML(http.StatusNotFound,"404.html",nil) }) userGroup := eng.Group("/user") { userGroup.GET("/index", func(context *gin.Context) { context.JSON(http.StatusOK,gin.H{"msg":"user_index"}) }) userGroup.GET("/login", func(context *gin.Context) { context.JSON(http.StatusOK,gin.H{"msg":"user_login"}) }) vipGroup := userGroup.Group("/vip") { vipGroup.GET("/index", func(context *gin.Context) { context.JSON(http.StatusOK,gin.H{"msg":"user_vip_index"}) }) vipGroup.GET("/login", func(context *gin.Context) { context.JSON(http.StatusOK,gin.H{"msg":"user_vip_login"}) }) } } adminGroup := eng.Group("/admin") { adminGroup.GET("/index", func(context *gin.Context) { context.JSON(http.StatusOK,gin.H{"msg":"admin_index"}) }) adminGroup.GET("/login", func(context *gin.Context) { context.JSON(http.StatusOK,gin.H{"msg":"admin_login"}) }) } eng.Run() } Gin 的绑定数据到结构体上:form表单,json格式, package main import ( "fmt" "github.com/gin-gonic/gin" "net/http" ) type myData struct { Username string `form:"username" json:"user" binding:"required"` Password string `form:"password" json:"pwd" binding:"required"` } func main() { eng :=gin.Default() eng.POST("/", func(context *gin.Context) { var d myData // Content-type 为 multipart/form-data // POST 表单上传 //err := context.Bind(&d) // Bind 可以解析form 格式 //if err != nil { // fmt.Println("bind data to struct failed,err:",err) // return //} //fmt.Println(d.Username) //fmt.Println(d.Password) //Content-type 为 application/json 格式 err := context.ShouldBindUri(&d) if err != nil { fmt.Println("bind data to struct failed,err:",err) return } fmt.Println(d.Username) fmt.Println(d.Password) context.JSON(http.StatusOK,gin.H{"msg":"ok"}) }) eng.Run() } uri:(path 路径) package main import ( "fmt" "github.com/gin-gonic/gin" "net/http" ) type myData struct { Username string `uri:"name" binding:"required"` Password string `uri:"pwd" binding:"required"` } func main() { eng :=gin.Default() eng.GET("/:name/:pwd", func(context *gin.Context) { var d myData err := context.ShouldBindUri(&d) if err != nil { fmt.Println("bind data to struct failed,err:",err) return } fmt.Println(d.Username) fmt.Println(d.Password) context.JSON(http.StatusOK,gin.H{"msg":"ok"}) }) eng.Run() }
Gin 的中间件:全局中间件(contex.Next() 和 context.Abort() ) package main import ( "fmt" "github.com/gin-gonic/gin" "net/http" "time" ) // 请求耗时的中间件函数 func countReqTime()gin.HandlerFunc { return func(context *gin.Context) { start := time.Now() m := make(map[string]interface{}) m["name"] = "tom" m["age"] = 18 context.Set("data",m) // 可以通过context.Set在请求上下文中设置值,后续的处理函数能够取到该值 time.Sleep(time.Second) res := time.Since(start) fmt.Println("耗时:",res) context.Next() } } // 打印 hello world 的中间件 func printHello()gin.HandlerFunc { return func(context *gin.Context) { fmt.Println("hello world") context.Next() // 如果使用 context.Abort() 请求会到此返回,洋葱模型 } } func main() { eng :=gin.Default() // 注册两个全局中间件 eng.Use(printHello()) eng.Use(countReqTime()) // {} 是为了代码规范 eng.GET("/", func(context *gin.Context) { fmt.Println(context.Get("data")) context.JSON(http.StatusOK,gin.H{"msg":"ok"}) }) eng.Run() }
局部中间件(给单个路由 设置中间件) package main import ( "fmt" "github.com/gin-gonic/gin" "net/http" ) // 打印 hello world 的中间件 func printHello()gin.HandlerFunc { return func(context *gin.Context) { fmt.Println("hello world") context.Next() // 如果使用 context.Abort() 请求会到此返回,洋葱模型 } } func main() { eng :=gin.Default() eng.GET("/",printHello(), func(context *gin.Context) { context.JSON(http.StatusOK,gin.H{"msg":"ok"}) }) eng.Run() }
给路由组加上中间件: package main import ( "fmt" "github.com/gin-gonic/gin" "net/http" ) func printHello() gin.HandlerFunc { return func(context *gin.Context) { fmt.Println("hello world") context.Next() } } func main() { eng :=gin.Default() eng.LoadHTMLGlob("templates/*") eng.NoRoute(func(context *gin.Context) { context.HTML(http.StatusNotFound,"404.html",nil) }) // 方式一 //userGroup := eng.Group("/user",printHello()) //{ // userGroup.GET("/index", func(context *gin.Context) { // context.JSON(http.StatusOK,gin.H{"msg":"user_index"}) // }) // userGroup.GET("/login", func(context *gin.Context) { // context.JSON(http.StatusOK,gin.H{"msg":"user_login"}) // }) //} // 方式二 userGroup := eng.Group("/user") userGroup.Use(printHello()) { userGroup.GET("/index", func(context *gin.Context) { context.JSON(http.StatusOK,gin.H{"msg":"user_index"}) }) userGroup.GET("/login", func(context *gin.Context) { context.JSON(http.StatusOK,gin.H{"msg":"user_login"}) }) } eng.Run() }
默认中间件:
Gin 的获取设置Cookie:package main import ( "fmt" "github.com/gin-gonic/gin" ) func main() { eng :=gin.Default() eng.GET("/", func(context *gin.Context) { // 获取客户端cookie cookie,err := context.Cookie("xxx" 全部评论
专题导读
热门推荐
热门话题
阅读排行榜
|
请发表评论