92 lines
2.2 KiB
Go
92 lines
2.2 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"kontor-api-gin/internal/config"
|
|
"kontor-api-gin/internal/globals"
|
|
"kontor-api-gin/internal/handlers"
|
|
"kontor-api-gin/internal/repository"
|
|
"kontor-api-gin/internal/router"
|
|
"kontor-api-gin/internal/service"
|
|
"log"
|
|
"log/slog"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"strconv"
|
|
"syscall"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
func main() {
|
|
slog.Info("Kontor started")
|
|
|
|
if err := globals.InitConfig(); err != nil {
|
|
log.Fatalf("Failed to initialize config: %v", err)
|
|
}
|
|
|
|
dsn := fmt.Sprintf(
|
|
"host=%s user=%s password=%s dbname=%s port=%d sslmode=disable",
|
|
viper.GetString("db.host"),
|
|
viper.GetString("db.user"),
|
|
viper.GetString("db.password"),
|
|
viper.GetString("db.name"),
|
|
viper.GetInt("db.port"),
|
|
)
|
|
|
|
db, err := config.NewDB(dsn)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
if err := db.AutoMigrate(); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
comicRepo := repository.NewComicRepository(db)
|
|
profileRepo := repository.NewProfileRepository(db)
|
|
comicService := service.NewComicService(comicRepo)
|
|
authService := service.NewAuthService(profileRepo, []byte(viper.GetString("api_secret")))
|
|
|
|
// Set Gin mode based on environment
|
|
// Production mode disables debug output
|
|
if viper.GetString("gin.mode") == "release" {
|
|
gin.SetMode(gin.ReleaseMode)
|
|
}
|
|
|
|
r := router.New(
|
|
&handlers.ComicHandler{Service: comicService},
|
|
&handlers.AuthHandler{Service: authService},
|
|
[]byte(viper.GetString("api_secret")),
|
|
)
|
|
// router.Use(sessions.Sessions("session", cookie.NewStore(globals.Secret)))
|
|
|
|
srv := &http.Server{
|
|
Addr: ":" + strconv.Itoa(viper.GetInt("port")),
|
|
Handler: r,
|
|
ReadHeaderTimeout: 5 * time.Second,
|
|
WriteTimeout: 30 * time.Second,
|
|
IdleTimeout: 120 * time.Second,
|
|
}
|
|
|
|
go func() {
|
|
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
|
log.Fatal(err)
|
|
}
|
|
}()
|
|
slog.Info("server up", "address", srv.Addr)
|
|
|
|
quit := make(chan os.Signal, 1)
|
|
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
|
|
<-quit
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
|
defer cancel()
|
|
_ = srv.Shutdown(ctx)
|
|
slog.Info("server stopped")
|
|
slog.Info("Kontor finished")
|
|
}
|