83 lines
2 KiB
Go
83 lines
2 KiB
Go
package main
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
|
|
apiv1 "git.ar21.de/yolokube/country-geo-locations/api/v1"
|
|
"git.ar21.de/yolokube/country-geo-locations/cfg"
|
|
"git.ar21.de/yolokube/country-geo-locations/internal/cache"
|
|
csvimporter "git.ar21.de/yolokube/country-geo-locations/internal/csv_importer"
|
|
"git.ar21.de/yolokube/country-geo-locations/internal/database"
|
|
"git.ar21.de/yolokube/country-geo-locations/internal/downloader"
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/go-chi/chi/v5/middleware"
|
|
"github.com/go-chi/render"
|
|
)
|
|
|
|
func main() {
|
|
cli := cfg.CLI{}
|
|
appSettings, err := cli.Parse()
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
handleGracefulShutdown()
|
|
|
|
ctx := downloader.NewContext(appSettings.DataFile, appSettings.DataURL)
|
|
if !ctx.FileExists() {
|
|
if downloadErr := ctx.Download(); downloadErr != nil {
|
|
log.Fatal(downloadErr)
|
|
}
|
|
log.Printf("saved file to %s\n", ctx.Filename)
|
|
}
|
|
|
|
db, err := database.NewDatabase()
|
|
if err != nil {
|
|
log.Fatal("database creation failed", err)
|
|
}
|
|
|
|
log.Println("importing data from file", appSettings.DataFile)
|
|
err = csvimporter.ImportCSV(appSettings.DataFile, db)
|
|
if err != nil {
|
|
log.Fatal("data Import from file failed", err)
|
|
}
|
|
log.Println("imported data from file successful")
|
|
|
|
cache := cache.NewCache(appSettings.CacheTTL)
|
|
lh := apiv1.NewLocationHandler(cache, db)
|
|
|
|
r := chi.NewRouter()
|
|
r.Use(middleware.RequestID)
|
|
r.Use(middleware.Logger)
|
|
r.Use(middleware.Recoverer)
|
|
r.Use(render.SetContentType(render.ContentTypeJSON))
|
|
|
|
r.Mount("/api/v1", apiv1.NewRouter(lh))
|
|
|
|
server := &http.Server{
|
|
Addr: appSettings.ServerAddress,
|
|
Handler: r,
|
|
ReadHeaderTimeout: appSettings.ReadHeaderTimeout,
|
|
}
|
|
|
|
log.Println("starting server at", server.Addr)
|
|
if err = server.ListenAndServe(); err != nil {
|
|
log.Panic(err)
|
|
}
|
|
}
|
|
|
|
func handleGracefulShutdown() {
|
|
var signals = make(chan os.Signal, 1)
|
|
|
|
signal.Notify(signals, syscall.SIGTERM, syscall.SIGINT)
|
|
|
|
go func() {
|
|
sig := <-signals
|
|
log.Printf("caught signal: %+v", sig)
|
|
os.Exit(0)
|
|
}()
|
|
}
|