forked from gin-gonic/examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
68 lines (45 loc) · 1.16 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
58
59
60
61
62
63
64
65
66
67
68
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
// version 1
apiV1 := router.Group("/v1")
apiV1.GET("users", func(c *gin.Context) {
c.JSON(http.StatusOK, "List Of V1 Users")
})
// User only can be added by authorized person
authV1 := apiV1.Group("/", AuthMiddleWare())
authV1.POST("users/add", AddV1User)
//version 2
apiV2 := router.Group("/v2")
apiV2.GET("users", func(c *gin.Context) {
c.JSON(http.StatusOK, "List Of V2 Users")
})
// User only can be added by authorized person
authV2 := apiV2.Group("/", AuthMiddleWare())
authV2.POST("users/add", AddV2User)
_ = router.Run(":8081")
}
func AddV1User(c *gin.Context) {
// AddUser
c.JSON(http.StatusOK, "V1 User added")
}
func AddV2User(c *gin.Context) {
// AddUser
c.JSON(http.StatusOK, "V2 User added")
}
func AuthMiddleWare() gin.HandlerFunc {
return func(c *gin.Context) {
// here you can add your authentication method to authorize users.
username := c.PostForm("user")
password := c.PostForm("password")
if username == "foo" && password == "bar" {
return
} else {
c.AbortWithStatus(http.StatusUnauthorized)
}
}
}