gin(1)

数据绑定和解析

 1 package main
 2 
 3 import (
 4     "net/http"
 5 
 6     "github.com/gin-gonic/gin"
 7 )
 8 
 9 type Login struct {
10     User     string `form: "username" json: "user" uri: "user" xml: "user" binding: "required"`
11     Password string `form: "password" json: "password" uri: "password" xml: "password" binding: "password"`
12 }
13 
14 func main() {
15     r := gin.Default()
16     //JSON绑定
17     r.POST("/loginForm", func(c *gin.Context) {
18         var form Login
19         if err := c.Bind(&form); err != nil {
20             //gin.H封装了生成JSON数据的工具
21             c.JSON(http.StatusBadRequest, gin.H{
22                 "error": err.Error(),
23             })
24             return
25         }
26 
27         if form.User != "root" || form.Password != "admin" {
28             c.JSON(http.StatusBadRequest, gin.H{
29                 "status": "304",
30             })
31             return
32         }
33         c.JSON(http.StatusOK, gin.H{
34             "status": "200",
35         })
36     })
37     r.Run(":8080")
38 }
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>登陆</title>
 6 </head>
 7 <body>
 8 
 9     <form action="http://127.0.0.1:8080/loginForm" method="post" enctype="multipart/form-data">
10     用户名:<input type="text" name="username">
11     <br>
12&nbsp&nbsp码: <input type="password" name="password">
13     <input type="submit" value="登陆">
14 </form>
15 </body>
16 </html>

 

 

 

 

 1 package main
 2 
 3 import (
 4     "github.com/gin-gonic/gin"
 5     "github.com/gin-gonic/gin/testdata/protoexample"
 6 )
 7 
 8 func main() {
 9     r := gin.Default()
10     //JSON
11     r.GET("/someJSON", func(c *gin.Context) {
12         c.JSON(200, gin.H{
13             "message": "someJSON",
14             "status":  200,
15         })
16     })
17 
18     r.GET("/someStruct", func(c *gin.Context) {
19         var msg struct {
20             Name    string
21             Message string
22             Number  int
23         }
24         msg.Name = "root"
25         msg.Message = "message"
26         msg.Number = 123
27         c.JSON(200, msg)
28     })
29 
30     r.GET("/someXML", func(c *gin.Context) {
31         c.XML(200, gin.H{
32             "message": "abc",
33         })
34     })
35 
36     r.GET("/someYAML", func(c *gin.Context) {
37         c.YAML(200, gin.H{
38             "name": "cxk",
39         })
40     })
41 
42     r.GET("/someProtoBuf", func(c *gin.Context) {
43         reps := []int64{int64(1), int64(2)}
44 
45         label := "label"
46 
47         data := &protoexample.Test{
48             Label: &label,
49             Reps:  reps,
50         }
51         c.ProtoBuf(200, data)
52     })
53 
54     r.Run(":8080")
55 }

 

 

 渲染

 1 package main
 2 
 3 import (
 4     "github.com/gin-gonic/gin"
 5 )
 6 
 7 func main() {
 8     r := gin.Default()
 9 
10     r.LoadHTMLGlob("templates/*")
11     r.GET("/index", func(c *gin.Context) {
12         c.HTML(200, "index.tmpl", gin.H{
13             "title": "我的标题",
14         })
15     })
16     r.Run(":8080")
17 }

 重定向

 1 package main
 2 
 3 import (
 4     "net/http"
 5 
 6     "github.com/gin-gonic/gin"
 7 )
 8 
 9 func main() {
10     r := gin.Default()
11 
12     r.GET("/redirect", func(c *gin.Context) {
13         c.Redirect(http.StatusMovedPermanently, "http://www.bing.com/")
14     })
15     r.Run(":8080")
16 }

 

 同步异步

 1 package main
 2 
 3 import (
 4     "log"
 5     "time"
 6 
 7     "github.com/gin-gonic/gin"
 8 )
 9 
10 func main() {
11     r := gin.Default()
12 
13     r.GET("/long_async", func(c *gin.Context) {
14         copyContext := c.Copy()
15 
16         go func() {
17             time.Sleep(3 * time.Second)
18             log.Println("异步执行: " + copyContext.Request.URL.Path)
19         }()
20     })
21     //同步
22     r.GET("long_sync", func(c *gin.Context) {
23         time.Sleep(3 * time.Second)
24         log.Println("同步执行: " + c.Request.URL.Path)
25     })
26     r.Run(":8080")
27 }

 

 中间件

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "time"
 6 
 7     "github.com/gin-gonic/gin"
 8 )
 9 
10 func MiddleWare() gin.HandlerFunc {
11     return func(c *gin.Context) {
12         t := time.Now()
13         fmt.Println("中间件开始执行")
14         c.Set("request", "中间件")
15         c.Next()
16         status := c.Writer.Status()
17         fmt.Println("中间件执行完毕", status)
18 
19         t2 := time.Since(t)
20         fmt.Println("time: ", t2)
21     }
22 }
23 
24 func main() {
25     r := gin.Default()
26     //注册中间件
27     r.Use(MiddleWare())
28     {
29         r.GET("/middleware", func(c *gin.Context) {
30             req, _ := c.Get("request")
31             fmt.Println("request", req)
32             //页面接收
33             c.JSON(200, gin.H{
34                 "request": req,
35             })
36         })
37     }
38 
39     r.Run(":8080")
40 }

 

 

 

 

 

 

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "time"
 6 
 7     "github.com/gin-gonic/gin"
 8 )
 9 
10 func mytime(c *gin.Context) {
11     start := time.Now()
12     c.Next()
13 
14     since := time.Since(start)
15     fmt.Println("程序用时:", since)
16 }
17 
18 func main() {
19     r := gin.Default()
20     r.Use(mytime)
21     shoppingGroup := r.Group("/shopping")
22     {
23         shoppingGroup.GET("/index", shopIndexHandler)
24         shoppingGroup.GET("/home", shopHomeHandler)
25     }
26 
27     r.Run(":8080")
28 }
29 
30 func shopIndexHandler(c *gin.Context) {
31     time.Sleep(5 * time.Second)
32 }
33 
34 func shopHomeHandler(c *gin.Context) {
35     time.Sleep(3 * time.Second)
36 }

 

 Cookie

 1 package main
 2 
 3 import (
 4     "fmt"
 5 
 6     "github.com/gin-gonic/gin"
 7 )
 8 
 9 func main() {
10     r := gin.Default()
11     r.GET("cookie", func(c *gin.Context) {
12         cookie, err := c.Cookie("key_cookie")
13         if err != nil {
14             cookie = "NotSet"
15             c.SetCookie("key_cookie", "value_cookie", 60, "/",
16                 "localhost", false, true)
17         }
18         fmt.Printf("cookie的值是: %s\n", cookie)
19     })
20 
21     r.Run(":8080")
22 }

 

 

 1 package main
 2 
 3 import (
 4     "net/http"
 5 
 6     "github.com/gin-gonic/gin"
 7 )
 8 
 9 func AuthMiddleWare() gin.HandlerFunc {
10     return func(c *gin.Context) {
11         if cookie, err := c.Cookie("abc"); err == nil {
12             if cookie == "123" {
13                 c.Next()
14                 return
15             }
16         }
17         c.JSON(http.StatusUnauthorized, gin.H{
18             "error": "err",
19         })
20         c.Abort()
21         return
22     }
23 }
24 
25 func main() {
26     r := gin.Default()
27     r.GET("/login", func(c *gin.Context) {
28         c.SetCookie("abc", "123", 60, "/",
29             "localhost", false, true)
30 
31         c.String(200, "Login success!")
32     })
33     r.GET("/home", AuthMiddleWare(), func(c *gin.Context) {
34         c.JSON(200, gin.H{
35             "data": "home",
36         })
37     })
38     r.Run(":8080")
39 }

 

 

 

 

 

 

 

posted @ 2019-11-28 12:22  尘归风  阅读(243)  评论(0)    收藏  举报