-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
123 lines (98 loc) · 2.5 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
package main
import (
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/akrylysov/pogreb"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/robfig/cron/v3"
)
type Server struct {
app *fiber.App
url string
cache *pogreb.DB
cron *cron.Cron
authorizeKey string
corsOrigin string
}
func main() {
var authorKey string = os.Getenv("AUTHORIZE_KEY")
if authorKey == "" {
panic("Can't find AUTHORIZE_KEY in environment")
}
var port string = os.Getenv("PORT")
if port == "" {
panic("Can't find PORT in environment")
}
// can be * or http://1, http://2
var corsOrigin string = os.Getenv("CORS_ORIGIN")
if corsOrigin == "" {
panic("Can't find corsOrigin in environment")
}
cache, err := pogreb.Open(API_FILE_FOLDER, nil)
if err != nil {
panic(err)
}
var s *Server = &Server{
app: fiber.New(fiber.Config{
BodyLimit: 4 * 1024 * 1024,
RequestMethods: []string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"},
ErrorHandler: func(c *fiber.Ctx, err error) error {
return c.Status(fiber.StatusNotFound).SendString("hello")
// return utils.Render(c, layout.NotFoundComponents())
},
}),
url: port,
cache: cache,
cron: cron.New(
cron.WithParser(
cron.NewParser(
cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow))),
authorizeKey: authorKey,
corsOrigin: corsOrigin,
}
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
fmt.Println("Saving data to cache . . .")
_, err = handleCache(s.cache, s.authorizeKey)
if err != nil {
panic(err)
}
_, err = s.cron.AddFunc("0 */15 * * * *", func() {
fmt.Println("Cronjob saving data into cache: ", time.Now())
_, err := handleCache(s.cache, s.authorizeKey)
if err != nil {
return
}
})
if err != nil {
panic(err)
}
s.cron.Start()
cron.New(cron.WithSeconds())
go s.gracefulShutdown(quit)
s.app.Use(cors.New(cors.Config{
AllowOrigins: corsOrigin,
}))
cacheApi := newCacheApi(s.cache, s.authorizeKey)
s.app.Get("/api", cacheApi.HandleCacheApi)
s.httpListening()
}
func (s *Server) httpListening() {
if err := s.app.Listen(s.url); err != nil && err != http.ErrServerClosed {
log.Fatalf("Error: %v", err)
}
}
func (s *Server) gracefulShutdown(quit <-chan os.Signal) {
log.Printf("Starting service latest")
<-quit
log.Printf("Shutting down service")
if err := s.app.Shutdown(); err != nil {
log.Fatalf("Error: %v", err)
}
}