payment-poc/main.go

84 lines
1.9 KiB
Go

package main
import (
"embed"
"github.com/gin-gonic/gin"
"github.com/joho/godotenv"
"log/slog"
"net/http"
"os"
"payment-poc/api"
"payment-poc/migration"
"runtime/debug"
"strings"
)
//go:embed db/dev/*.sql
var devMigrations embed.FS
func init() {
godotenv.Load()
if !hasProfile("dev") {
gin.SetMode(gin.ReleaseMode)
}
if value := os.Getenv("LOG_FORMAT"); value == "json" {
slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{AddSource: true})))
}
}
func main() {
commit, buildTime := buildInfo()
slog.Info("build info", slog.String("commit", commit), slog.String("time", buildTime))
client, err := connectToDb()
if err != nil {
slog.Error("couldn't connect to db", slog.String("err", err.Error()))
os.Exit(1)
}
if err := migration.InitializeMigrations(client, devMigrations); err != nil {
slog.Error("couldn't finish migration", slog.String("err", err.Error()))
os.Exit(1)
}
server := api.SetupServer(client)
port := ":" + getOrDefault("SERVER_PORT", "5281")
slog.Info("app is ready", slog.String("port", port))
if err := http.ListenAndServe(port, server); err != nil {
slog.Error("Couldn't start server!\n", slog.Any("err", err.Error()))
}
}
func hasProfile(profile string) bool {
profiles := strings.Split(os.Getenv("PROFILE"), ",")
for _, p := range profiles {
if profile == strings.TrimSpace(p) {
return true
}
}
return false
}
func buildInfo() (string, string) {
revision := ""
buildTime := ""
if info, ok := debug.ReadBuildInfo(); ok {
for _, setting := range info.Settings {
if setting.Key == "vcs.revision" {
revision = setting.Value
} else if setting.Key == "vcs.time" {
buildTime = setting.Value
}
}
}
return revision, buildTime
}
func getOrDefault(env string, defaultValue string) string {
if value, present := os.LookupEnv(env); present {
return value
}
return defaultValue
}