forked from abelanger5/gin-example
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
57 lines (46 loc) · 1.33 KB
/
main.go
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
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
// simulate some test accounts
var secrets = gin.H{
"joe": gin.H{"email": "[email protected]"},
"ivan": gin.H{"email": "[email protected]"},
}
func setupRouter() *gin.Engine {
r := gin.Default()
// Group using gin.BasicAuth() middleware
// gin.Accounts is a shortcut for map[string]string
authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{
"joe": "bornintheusa",
"ivan": "backintheussr",
}))
r.GET("/ping", func(c *gin.Context) {
fmt.Println("REQUEST HEADERS ==> ")
fmt.Println(c.Request.Header)
fmt.Println("CLIENT IP IS", c.ClientIP())
c.String(http.StatusOK, "pong")
})
r.GET("/ready", func(c *gin.Context) {
fmt.Println("Received an unauthenticated healthcheck.")
c.String(http.StatusOK, "check!")
})
authorized.GET("/readyz", func(c *gin.Context) {
// get user, it was set by the BasicAuth middleware
user := c.MustGet(gin.AuthUserKey).(string)
if secret, ok := secrets[user]; ok {
fmt.Println("Received an authenicated healthcheck.")
c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})
} else {
c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("})
}
})
return r
}
func main() {
r := setupRouter()
// Listen and Server in 0.0.0.0:8080
r.Run(":8080")
}