-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
110 lines (78 loc) · 2.37 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package main
import (
"log"
"os"
"io"
"github.com/asaskevich/govalidator"
"github.com/gin-gonic/gin"
"github.com/go-vote/handler"
"github.com/go-vote/middleware"
"github.com/joho/godotenv"
)
func init() {
err := godotenv.Load()
if err != nil {
log.Printf("Error loading .env file")
}
var port = "8080"
if len(port) == 0 {
log.Panic("no given port")
}
}
// Init libs, loggerS...
func initLibs() {
f, _ := os.Create("gin.log")
gin.DefaultWriter = io.MultiWriter(f)
gin.DisableConsoleColor()
govalidator.SetFieldsRequiredByDefault(false)
}
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Max-Age", "86400")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, PATCH, DELETE, UPDATE")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Access-Control-Allow-Origin, Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(200)
} else {
c.Next()
}
}
}
func initRouter() *gin.Engine {
r := gin.Default()
r.Use(CORSMiddleware())
r.Use(gin.Recovery())
r.Use(gin.Logger())
r.Use(middleware.IPFirewall())
r.POST("/login", middleware.LoginHandler)
r.GET("/", handler.BasicResponse)
r.POST("/users", handler.PostUser)
auth := r.Group("/")
auth.Use(middleware.JwtTokenCheck)
{
auth.GET("/users", handler.GetUsers)
auth.GET("/users/:uuid", handler.GetUser)
auth.GET("/login/me", handler.GetCurrentUser)
auth.PATCH("/responses/:uuid/vote", handler.Vote)
auth.DELETE("/responses/:uuid/vote", handler.DeleteVote)
auth.GET("/surveys", handler.GetSurveys)
auth.GET("/surveys/:uuid", handler.GetSurvey)
auth.POST("/surveys", handler.PostSurvey)
auth.PATCH("/responses/:uuid", handler.PatchResponse)
// Admin only protected routes
admin := auth.Group("/")
admin.Use(middleware.ACLCheck)
admin.PATCH("/users/:uuid", handler.PatchUser)
admin.DELETE("/users/:uuid", handler.DeleteUser)
admin.PATCH("/users/:uuid/promote", handler.PromoteUser)
admin.DELETE("/surveys/:uuid", handler.DeleteSurvey)
}
return r
}
func main() {
r := initRouter()
r.Run()
}