-
Notifications
You must be signed in to change notification settings - Fork 192
/
main.go
151 lines (120 loc) · 3.94 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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
package main
import (
"fmt"
"log"
"net/http"
"os"
"runtime"
"github.com/Massad/gin-boilerplate/controllers"
"github.com/Massad/gin-boilerplate/db"
"github.com/Massad/gin-boilerplate/forms"
"github.com/gin-contrib/gzip"
uuid "github.com/google/uuid"
"github.com/joho/godotenv"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
)
//CORSMiddleware ...
//CORS (Cross-Origin Resource Sharing)
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "http://localhost")
c.Writer.Header().Set("Access-Control-Max-Age", "86400")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
c.Writer.Header().Set("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding, x-access-token")
c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
if c.Request.Method == "OPTIONS" {
fmt.Println("OPTIONS")
c.AbortWithStatus(200)
} else {
c.Next()
}
}
}
//RequestIDMiddleware ...
//Generate a unique ID and attach it to each request for future reference or use
func RequestIDMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
uuid := uuid.New()
c.Writer.Header().Set("X-Request-Id", uuid.String())
c.Next()
}
}
var auth = new(controllers.AuthController)
//TokenAuthMiddleware ...
//JWT Authentication middleware attached to each request that needs to be authenitcated to validate the access_token in the header
func TokenAuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
auth.TokenValid(c)
c.Next()
}
}
func main() {
//Load the .env file
err := godotenv.Load(".env")
if err != nil {
log.Fatal("error: failed to load the env file")
}
if os.Getenv("ENV") == "PRODUCTION" {
gin.SetMode(gin.ReleaseMode)
}
//Start the default gin server
r := gin.Default()
//Custom form validator
binding.Validator = new(forms.DefaultValidator)
r.Use(CORSMiddleware())
r.Use(RequestIDMiddleware())
r.Use(gzip.Gzip(gzip.DefaultCompression))
//Start PostgreSQL database
//Example: db.GetDB() - More info in the models folder
db.Init()
//Start Redis on database 1 - it's used to store the JWT but you can use it for anythig else
//Example: db.GetRedis().Set(KEY, VALUE, at.Sub(now)).Err()
db.InitRedis(1)
v1 := r.Group("/v1")
{
/*** START USER ***/
user := new(controllers.UserController)
v1.POST("/user/login", user.Login)
v1.POST("/user/register", user.Register)
v1.GET("/user/logout", user.Logout)
/*** START AUTH ***/
auth := new(controllers.AuthController)
//Refresh the token when needed to generate new access_token and refresh_token for the user
v1.POST("/token/refresh", auth.Refresh)
/*** START Article ***/
article := new(controllers.ArticleController)
v1.POST("/article", TokenAuthMiddleware(), article.Create)
v1.GET("/articles", TokenAuthMiddleware(), article.All)
v1.GET("/article/:id", TokenAuthMiddleware(), article.One)
v1.PUT("/article/:id", TokenAuthMiddleware(), article.Update)
v1.DELETE("/article/:id", TokenAuthMiddleware(), article.Delete)
}
r.LoadHTMLGlob("./public/html/*")
r.Static("/public", "./public")
r.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.html", gin.H{
"ginBoilerplateVersion": "v0.03",
"goVersion": runtime.Version(),
})
})
r.NoRoute(func(c *gin.Context) {
c.HTML(404, "404.html", gin.H{})
})
port := os.Getenv("PORT")
log.Printf("\n\n PORT: %s \n ENV: %s \n SSL: %s \n Version: %s \n\n", port, os.Getenv("ENV"), os.Getenv("SSL"), os.Getenv("API_VERSION"))
if os.Getenv("SSL") == "TRUE" {
//Generated using sh generate-certificate.sh
SSLKeys := &struct {
CERT string
KEY string
}{
CERT: "./cert/myCA.cer",
KEY: "./cert/myCA.key",
}
r.RunTLS(":"+port, SSLKeys.CERT, SSLKeys.KEY)
} else {
r.Run(":" + port)
}
}