70 lines
1.6 KiB
Go
70 lines
1.6 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
|
|
api_v1 "git.ar21.de/yolokube/country-geo-locations/api/v1"
|
|
"git.ar21.de/yolokube/country-geo-locations/cfg"
|
|
"git.ar21.de/yolokube/country-geo-locations/pkg/downloader"
|
|
"git.ar21.de/yolokube/country-geo-locations/pkg/geoloc"
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/go-chi/chi/v5/middleware"
|
|
"github.com/go-chi/render"
|
|
)
|
|
|
|
func main() {
|
|
appSettings := cfg.NewAppSettings()
|
|
if err := appSettings.Parse(); err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
handleGracefulShutdown()
|
|
|
|
ctx := downloader.NewContext(appSettings.DataFile, appSettings.DataURL)
|
|
if !ctx.FileExists() {
|
|
if err := ctx.Download(); err != nil {
|
|
panic(err)
|
|
}
|
|
fmt.Printf("Saved file to %s\n", ctx.Filename)
|
|
}
|
|
|
|
fmt.Printf("Import data from file...\r")
|
|
err := geoloc.ImportCSV(appSettings.DataFile)
|
|
if err != nil {
|
|
fmt.Println("Import data from file failed")
|
|
panic(err)
|
|
}
|
|
fmt.Println("Import data from file successful")
|
|
|
|
geoloc.IPCache = geoloc.NewCache()
|
|
fmt.Println("Cache created")
|
|
|
|
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", api_v1.ApiRouter())
|
|
|
|
log.Printf("starting server at %s\n", appSettings.ServerAddress)
|
|
http.ListenAndServe(appSettings.ServerAddress, r)
|
|
}
|
|
|
|
func handleGracefulShutdown() {
|
|
var signals = make(chan os.Signal, 1)
|
|
|
|
signal.Notify(signals, syscall.SIGTERM)
|
|
signal.Notify(signals, syscall.SIGINT)
|
|
|
|
go func() {
|
|
sig := <-signals
|
|
log.Printf("caught signal: %+v", sig)
|
|
os.Exit(0)
|
|
}()
|
|
}
|