Skip to content

Commit 4ec81e2

Browse files
committed
copied gin framework basic example
1 parent ea65394 commit 4ec81e2

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

main.go

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package main
2+
3+
import (
4+
"net/http"
5+
6+
"github.com/gin-gonic/gin"
7+
)
8+
9+
var db = make(map[string]string)
10+
11+
func setupRouter() *gin.Engine {
12+
// Disable Console Color
13+
// gin.DisableConsoleColor()
14+
r := gin.Default()
15+
16+
// Ping test
17+
r.GET("/ping", func(c *gin.Context) {
18+
c.String(http.StatusOK, "pong")
19+
})
20+
21+
// Get user value
22+
r.GET("/user/:name", func(c *gin.Context) {
23+
user := c.Params.ByName("name")
24+
value, ok := db[user]
25+
if ok {
26+
c.JSON(http.StatusOK, gin.H{"user": user, "value": value})
27+
} else {
28+
c.JSON(http.StatusOK, gin.H{"user": user, "status": "no value"})
29+
}
30+
})
31+
32+
// Authorized group (uses gin.BasicAuth() middleware)
33+
// Same than:
34+
// authorized := r.Group("/")
35+
// authorized.Use(gin.BasicAuth(gin.Credentials{
36+
// "foo": "bar",
37+
// "manu": "123",
38+
//}))
39+
authorized := r.Group("/", gin.BasicAuth(gin.Accounts{
40+
"foo": "bar", // user:foo password:bar
41+
"manu": "123", // user:manu password:123
42+
}))
43+
44+
authorized.POST("admin", func(c *gin.Context) {
45+
user := c.MustGet(gin.AuthUserKey).(string)
46+
47+
// Parse JSON
48+
var json struct {
49+
Value string `json:"value" binding:"required"`
50+
}
51+
52+
if c.Bind(&json) == nil {
53+
db[user] = json.Value
54+
c.JSON(http.StatusOK, gin.H{"status": "ok"})
55+
}
56+
})
57+
58+
return r
59+
}
60+
61+
func main() {
62+
r := setupRouter()
63+
// Listen and Server in 0.0.0.0:8080
64+
r.Run(":8080")
65+
}

0 commit comments

Comments
 (0)