-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
126 lines (105 loc) · 2.51 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
package main
import (
"net/http"
"os"
"regexp"
"strings"
"time"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
var (
DbUrl string
Db sql.DB
)
func main() {
gin.SetMode(gin.ReleaseMode)
Db = *SetUpDb()
defer Db.Close()
router := gin.New()
corsConfig := getCORSConfig()
if corsConfig != nil {
router.Use(corsConfig)
}
router.POST("/record_event", RecordEvent)
router.GET("/health", healthCheckHandler)
log.Fatal(router.Run(":8085"))
}
func SetUpDb() (db *sql.DB) {
DbUrl = fmt.Sprintf(
"postgres://%s:%s@%s:%s/%s?client_encoding=utf8",
os.Getenv("DB_USER"),
os.Getenv("DB_PASS"),
os.Getenv("DB_HOST"),
os.Getenv("DB_PORT"),
os.Getenv("DB_NAME"),
)
db, err := sql.Open("postgres", DbUrl)
if err != nil {
log.WithFields(log.Fields{
"custom_msg": "Unsucessfully connected with db",
}).Error(err)
panic(err)
}
if err = db.Ping(); err != nil {
log.WithFields(log.Fields{
"custom_msg": "Unsucessfully connected with db",
}).Error(err)
panic(err)
}
fmt.Println("Successfully connected to db")
return
}
func getCORSConfig() gin.HandlerFunc {
env := os.Getenv("ENV")
switch env {
case "production":
allowedOrigins := strings.Split(os.Getenv("ALLOWED_ORIGINS"), ",")
allowedPatterns := strings.Split(os.Getenv("ALLOWED_PATTERNS"), ",")
return cors.New(cors.Config{
AllowOriginFunc: func(origin string) bool {
// Check exact matches
for _, allowedOrigin := range allowedOrigins {
if allowedOrigin == origin {
return true
}
}
// Check patterns
for _, pattern := range allowedPatterns {
if pattern != "" {
if matched, _ := regexp.MatchString("^"+pattern+"$", origin); matched {
return true
}
}
}
return false
},
AllowMethods: []string{"POST", "OPTIONS", "GET"},
AllowHeaders: []string{"Origin", "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization", "Accept", "Cache-Control", "X-Requested-With"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true,
MaxAge: 12 * time.Hour,
})
case "staging":
return cors.Default()
default:
return nil
}
}
func healthCheckHandler(c *gin.Context) {
if err := Db.Ping(); err != nil {
c.JSON(
http.StatusInternalServerError,
gin.H{"status": "error", "message": "Database is disconnected"},
)
return
}
c.JSON(
http.StatusOK,
gin.H{"status": "success", "message": "API is healthy"},
)
}