-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
69 lines (61 loc) · 1.98 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
package main
import (
"flag"
"log"
"os"
"os/signal"
"strconv"
"syscall"
"time"
"github.com/joho/godotenv"
"github.com/njo/nfcache/pkg/apiclient"
"github.com/njo/nfcache/pkg/apiserver"
"github.com/njo/nfcache/pkg/datasource"
"go.uber.org/zap"
)
func main() {
// Load CLI Options
var port int
flag.IntVar(&port, "p", 8080, "Set the port number to listen on (Default 8080)")
flag.Parse()
// Set up logger
zLogger, err := zap.NewProduction()
if err != nil {
log.Fatalf("can't initialize zap logger: %v\n", err)
}
defer zLogger.Sync() // ensure logger buffer flushed on shutdown
logger := zLogger.Sugar() // Sugar logger allows for printf style formatting
// Load env vars
err = godotenv.Load() // Adds .env file into regular os.env vars
if err == nil {
logger.Info("Loaded .env file")
}
githubToken := os.Getenv("GITHUB_API_TOKEN")
if githubToken == "" {
logger.Warn("Unable to load GITHUB_API_TOKEN")
}
// Init servers
githubClient := apiclient.NewGithub(githubToken)
apiCache := datasource.NewCachedAPI(githubClient, logger)
server := apiserver.New(apiCache, logger)
initalEndpoints := apiserver.CachedEndpoints()
logger.Info("Pre-fetching initial endpoint data")
for _, path := range initalEndpoints {
logger.Infof("Fetching %s", path)
err = apiCache.WatchEndpoint(path)
if err != nil {
// Choosing to early exit here as there's probably an external api issue
logger.Fatalf("unable to fetch %s on startup: %v\n", path, err)
}
}
apiCache.Run(datasource.DefaultUpdateIntervalSec * time.Second) // Keeps the cache updated in the background
listenAddress := ":" + strconv.Itoa(port)
go server.Run(listenAddress) // Run the service in a separate thread to not block signal handler
// Wait for shutdown signals
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
server.Shutdown(5 * time.Second)
apiCache.Shutdown() // Can take a bit if we're in the middle of a cache update
logger.Info("Service gracefully exited")
}