-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
120 lines (98 loc) · 3.08 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
package main
import (
"log"
"net/http"
"os"
"time"
"github.com/gin-contrib/static"
"github.com/gin-gonic/gin"
"go.mongodb.org/mongo-driver/mongo"
"github.com/rankitbishnoi-srijan/gopcommerce/src/db"
"github.com/rankitbishnoi-srijan/gopcommerce/src/packages/auth"
"github.com/rankitbishnoi-srijan/gopcommerce/src/packages/users"
"github.com/rankitbishnoi-srijan/gopcommerce/src/utils"
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
)
func NewRouter(db *mongo.Client) *gin.Engine {
// Set the router as the default one shipped with Gin
router := gin.New()
expectedHost := "localhost:8080"
// Setup middleware
router.Use(gin.Logger())
router.Use(gin.Recovery())
router.Use(DBMiddleware(db))
// Setup Security Headers
router.Use(func(c *gin.Context) {
if c.Request.Host != expectedHost {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid host header"})
return
}
c.Header("X-Frame-Options", "DENY")
c.Header("Content-Security-Policy", "default-src 'self'; connect-src *; font-src *; script-src-elem * 'unsafe-inline'; img-src * data:; style-src * 'unsafe-inline';")
c.Header("X-XSS-Protection", "1; mode=block")
c.Header("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload")
c.Header("Referrer-Policy", "strict-origin")
c.Header("X-Content-Type-Options", "nosniff")
c.Header("Permissions-Policy", "geolocation=(),midi=(),sync-xhr=(),microphone=(),camera=(),magnetometer=(),gyroscope=(),fullscreen=(self),payment=()")
c.Next()
})
// Serve frontend static files
router.Use(static.Serve("/", static.LocalFile("./public/", true)))
// serve swagger ui with openapi.yml
router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler,
ginSwagger.URL("http://localhost:8080/openapi.yml")))
// Setup route group for the API
api := router.Group("/api")
{
apiHandler := func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "Uniform API",
})
}
api.GET("", apiHandler)
api.GET("/", apiHandler)
auth.RegisterHandlers(api)
users.RegisterHandlers(api)
}
return router
}
// DBMiddleware will add the db connection to the context
func DBMiddleware(db *mongo.Client) gin.HandlerFunc {
return func(c *gin.Context) {
c.Set("databaseConn", db)
c.Next()
}
}
func main() {
// Load environment variables
if err := utils.LoadEnv(); err != nil {
log.Fatalf("Failed to load environment variables: %v", err)
}
httpPort := os.Getenv("PORT")
if httpPort == "" {
httpPort = "8080"
}
// Initialize MongoDB
uri := os.Getenv("MONGODB_URI")
if uri == "" {
log.Fatal("MONGODB_URI must be set")
}
client, err := db.Connect(uri)
if err != nil {
log.Fatalf("Failed to connect to MongoDB: %v", err)
}
defer db.Disconnect(client)
// Initialize router
router := NewRouter(client)
// Create server with timeout
srv := &http.Server{
Addr: ":" + httpPort,
Handler: router,
// set timeout due CWE-400 - Potential Slowloris Attack
ReadHeaderTimeout: 5 * time.Second,
}
if err := srv.ListenAndServe(); err != nil {
log.Printf("Failed to start server: %v", err)
}
}