payment-poc/main.go

84 lines
1.9 KiB
Go
Raw Permalink Normal View History

2023-07-06 11:29:06 +00:00
package main
import (
"embed"
"github.com/gin-gonic/gin"
"github.com/joho/godotenv"
2024-04-01 18:29:24 +00:00
"log/slog"
2023-07-06 11:29:06 +00:00
"net/http"
2023-07-27 20:46:37 +00:00
"os"
2024-04-01 18:29:24 +00:00
"payment-poc/api"
2023-07-10 08:10:13 +00:00
"payment-poc/migration"
2024-04-01 18:29:24 +00:00
"runtime/debug"
2023-07-10 08:10:13 +00:00
"strings"
2023-07-06 11:29:06 +00:00
)
//go:embed db/dev/*.sql
var devMigrations embed.FS
func init() {
godotenv.Load()
2024-04-01 18:29:24 +00:00
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})))
}
2023-07-06 11:29:06 +00:00
}
func main() {
2024-04-01 18:29:24 +00:00
commit, buildTime := buildInfo()
slog.Info("build info", slog.String("commit", commit), slog.String("time", buildTime))
2023-07-06 11:29:06 +00:00
client, err := connectToDb()
if err != nil {
2024-04-01 18:29:24 +00:00
slog.Error("couldn't connect to db", slog.String("err", err.Error()))
os.Exit(1)
2023-07-06 11:29:06 +00:00
}
if err := migration.InitializeMigrations(client, devMigrations); err != nil {
2024-04-01 18:29:24 +00:00
slog.Error("couldn't finish migration", slog.String("err", err.Error()))
os.Exit(1)
2023-07-06 11:29:06 +00:00
}
2024-04-01 18:29:24 +00:00
server := api.SetupServer(client)
2023-07-10 08:10:13 +00:00
2024-04-01 18:29:24 +00:00
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()))
}
2023-07-27 20:46:37 +00:00
}
2023-07-10 08:10:13 +00:00
2023-07-27 20:46:37 +00:00
func hasProfile(profile string) bool {
profiles := strings.Split(os.Getenv("PROFILE"), ",")
for _, p := range profiles {
if profile == strings.TrimSpace(p) {
return true
2023-07-10 08:10:13 +00:00
}
2023-07-27 20:46:37 +00:00
}
return false
}
2023-07-10 08:10:13 +00:00
2024-04-01 18:29:24 +00:00
func buildInfo() (string, string) {
revision := ""
buildTime := ""
2023-07-27 20:46:37 +00:00
2024-04-01 18:29:24 +00:00
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
}
}
2023-07-31 07:21:54 +00:00
}
2024-04-01 18:29:24 +00:00
return revision, buildTime
2023-07-31 07:21:54 +00:00
}
2024-04-01 18:29:24 +00:00
func getOrDefault(env string, defaultValue string) string {
if value, present := os.LookupEnv(env); present {
return value
2023-07-27 20:46:37 +00:00
}
2024-04-01 18:29:24 +00:00
return defaultValue
2023-07-10 08:10:13 +00:00
}