-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
210 lines (178 loc) · 5.44 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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package main
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
"github.com/alicebob/miniredis/v2"
"github.com/anandvarma/namegen"
"github.com/redis/go-redis/v9"
"github.com/jasonlovesdoggo/abacus/middleware"
"github.com/gin-contrib/cors"
analytics "github.com/tom-draper/api-analytics/analytics/go/gin"
"github.com/jasonlovesdoggo/abacus/utils"
"github.com/gin-gonic/gin"
)
const (
DocsUrl string = "https://jasoncameron.dev/abacus/"
Version string = "1.3.3"
)
var (
Client *redis.Client
RateLimitClient *redis.Client
DbNum = 0 // 0-16
StartTime time.Time
Shard string
)
func init() {
utils.LoadEnv()
// Use miniredis for testing
if strings.ToLower(os.Getenv("TESTING")) == "true" {
setupMockRedis()
return
}
// Production Redis setup
Shard = namegen.New().Get()
if strings.ToLower(os.Getenv("DEBUG")) == "true" {
gin.SetMode(gin.DebugMode)
} else {
gin.SetMode(gin.ReleaseMode)
}
ADDR := os.Getenv("REDIS_HOST") + ":" + os.Getenv("REDIS_PORT")
log.Println("Listening to redis on: " + ADDR)
DbNum, _ = strconv.Atoi(os.Getenv("REDIS_DB"))
Client = redis.NewClient(&redis.Options{
Addr: ADDR, // Redis server address
Username: os.Getenv("REDIS_USERNAME"),
Password: os.Getenv("REDIS_PASSWORD"),
DB: DbNum,
})
RateLimitClient = redis.NewClient(&redis.Options{
Addr: ADDR, // Redis server address
Username: os.Getenv("REDIS_USERNAME"),
Password: os.Getenv("REDIS_PASSWORD"),
DB: DbNum + 1,
})
}
func setupMockRedis() {
// Used for testing, "miniredis" is a mock Redis server that runs in-memory for testing purposes only (no persistence)
mr, err := miniredis.Run()
if err != nil {
log.Fatalf("Failed to start miniredis: %v", err)
}
log.Println("Using miniredis for testing")
// Connect clients to miniredis
Client = redis.NewClient(&redis.Options{
Addr: mr.Addr(),
})
RateLimitClient = redis.NewClient(&redis.Options{
Addr: mr.Addr(),
})
}
func CreateRouter() *gin.Engine {
utils.InitializeStatsManager(Client)
r := gin.Default()
// Cors
corsConfig := cors.Config{
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Length", "Content-Type", "Authorization"},
AllowCredentials: false,
AllowAllOrigins: true,
MaxAge: 12 * time.Hour,
}
r.Use(cors.New(corsConfig))
r.Use(gin.Recovery()) // recover from panics and returns a 500 error
if os.Getenv("API_ANALYTICS_ENABLED") == "true" {
r.Use(analytics.Analytics(os.Getenv("API_ANALYTICS_KEY"))) // Add middleware
log.Println("Analytics enabled")
}
route := r.Group("")
route.Use(middleware.Stats())
if os.Getenv("RATE_LIMIT_ENABLED") == "true" {
route.Use(middleware.RateLimit(RateLimitClient))
log.Println("Rate limiting enabled")
}
// Define routes
r.NoRoute(func(c *gin.Context) {
c.Redirect(http.StatusPermanentRedirect, DocsUrl)
})
// heath check
r.StaticFile("/favicon.svg", "./assets/favicon.svg")
r.StaticFile("/favicon.ico", "./assets/favicon.ico")
{ // Stats Routes
route.GET("/healthcheck", func(context *gin.Context) {
context.JSON(http.StatusOK, gin.H{
"status": "ok", "uptime": time.Since(StartTime).String()})
})
route.GET("/docs", func(context *gin.Context) {
context.Redirect(http.StatusPermanentRedirect, DocsUrl)
})
route.GET("/stats", StatsView)
}
{ // Public Routes
route.GET("/get/:namespace/*key", GetView)
route.GET("/hit/:namespace/*key", HitView)
route.GET("/stream/:namespace/*key", middleware.SSEMiddleware(), StreamValueView)
route.POST("/create/:namespace/*key", CreateView)
route.GET("/create/:namespace/*key", CreateView)
route.GET("/create/", CreateRandomView)
route.POST("/create/", CreateRandomView)
route.GET("/info/:namespace/*key", InfoView)
}
authorized := route.Group("")
authorized.Use(middleware.Auth(Client))
{ // Authorized Routes
authorized.POST("/delete/:namespace/*key", DeleteView)
authorized.POST("/set/:namespace/*key", SetView)
authorized.POST("/reset/:namespace/*key", ResetView)
authorized.POST("/update/:namespace/*key", UpdateByView)
}
return r
}
func main() {
//gin.SetMode(gin.ReleaseMode)
// only run the following if .env is present
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
utils.LoadEnv()
StartTime = time.Now()
// Initialize the Gin router
r := CreateRouter()
srv := &http.Server{ // #nosec G112 -- Due to the use of SSE endpoints, we cannot close the server early
Addr: ":" + os.Getenv("PORT"),
Handler: r,
}
fmt.Println("Listening on port " + os.Getenv("PORT"))
go func() {
// service connections
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("listen: %s\n", err)
}
}()
// Wait for interrupt signal to gracefully shutdown the server with
// a timeout of 5 seconds.
quit := make(chan os.Signal, 1)
// kill (no param) default send syscall.SIGTERM
// kill -2 is syscall.SIGINT
// kill -9 is syscall. SIGKILL but can"t be catch, so don't need add it
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
close(utils.ServerClose)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatal("Server Shutdown:", err)
}
select {
case <-ctx.Done():
log.Println("timeout of 5 seconds.")
}
log.Println("Server exiting")
}