介绍

文档 https://gin-gonic.com/zh-cn/docs/

直接就跑起来了

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
~~~
package main

import (
   "net/http"

   "github.com/gin-gonic/gin"
)

var db = make(map[string]string)

func setupRouter() *gin.Engine {
   // Disable Console Color
   // gin.DisableConsoleColor()
   r := gin.Default()

   // Ping test
   r.GET("/ping", func(c *gin.Context) {
      c.String(http.StatusOK, "pong")
   })

   // Get user value
   r.GET("/user/:name", func(c *gin.Context) {
      user := c.Params.ByName("name")
      value, ok := db[user]
      if ok {
         c.JSON(http.StatusOK, gin.H{"user": user, "value": value})
      } else {
         c.JSON(http.StatusOK, gin.H{"user": user, "status": "no value"})
      }
   })

   // Authorized group (uses gin.BasicAuth() middleware)
   // Same than:
   // authorized := r.Group("/")
   // authorized.Use(gin.BasicAuth(gin.Credentials{
   //   "foo":  "bar",
   //   "manu": "123",
   //}))
   authorized := r.Group("/", gin.BasicAuth(gin.Accounts{
      "foo":  "bar", // user:foo password:bar
      "manu": "123", // user:manu password:123
   }))

   authorized.POST("admin", func(c *gin.Context) {
      user := c.MustGet(gin.AuthUserKey).(string)

      // Parse JSON
      var json struct {
         Value string `json:"value" binding:"required"`
      }

      if c.Bind(&json) == nil {
         db[user] = json.Value
         c.JSON(http.StatusOK, gin.H{"status": "ok"})
      }
   })

   return r
}

func main() {
   r := setupRouter()
   // Listen and Server in 0.0.0.0:8080
   r.Run(":8080")
}
~~~