This repository has been archived on 2025-08-09. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
web-app-template/main.go

87 lines
1.8 KiB
Go

package main
import (
"me-fit/handler"
"me-fit/utils"
"context"
"database/sql"
"log"
"log/slog"
"net/http"
"os/signal"
"sync"
"syscall"
"time"
"github.com/joho/godotenv"
_ "github.com/mattn/go-sqlite3"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func main() {
run(context.Background())
}
func run(ctx context.Context) {
ctx, cancel := signal.NotifyContext(ctx, syscall.SIGINT, syscall.SIGTERM)
defer cancel()
slog.Info("Starting server...")
// init env
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
utils.MustInitEnv()
// init db
db, err := sql.Open("sqlite3", "./data.db")
if err != nil {
log.Fatal("Could not open Database data.db: ", err)
}
defer db.Close()
utils.MustRunMigrations(db, "")
// init servers
prometheusServer := &http.Server{
Addr: ":8081",
Handler: promhttp.Handler(),
}
httpServer := &http.Server{
Addr: ":8080",
Handler: handler.GetHandler(db),
}
go startServer(prometheusServer)
go startServer(httpServer)
// graceful shutdown
var wg sync.WaitGroup
wg.Add(2)
go shutdownServer(httpServer, ctx, &wg)
go shutdownServer(prometheusServer, ctx, &wg)
wg.Wait()
}
func startServer(s *http.Server) {
slog.Info("Starting server on " + s.Addr)
if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
slog.Error("error listening and serving: " + err.Error())
}
}
func shutdownServer(s *http.Server, ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done()
<-ctx.Done()
shutdownCtx := context.Background()
shutdownCtx, cancel := context.WithTimeout(shutdownCtx, 10*time.Second)
defer cancel()
if err := s.Shutdown(shutdownCtx); err != nil {
slog.Error("error shutting down http server: " + err.Error())
} else {
slog.Info("Gracefully stopped http server on " + s.Addr)
}
}