main.go
2.2 KB
| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "embed" |
| 6 | "errors" |
| 7 | "io/fs" |
| 8 | "log" |
| 9 | "net/http" |
| 10 | "os" |
| 11 | "os/signal" |
| 12 | "path/filepath" |
| 13 | "syscall" |
| 14 | "time" |
| 15 | |
| 16 | "github.com/clancore/repo/internal/auth" |
| 17 | "github.com/clancore/repo/internal/db" |
| 18 | "github.com/clancore/repo/internal/handlers" |
| 19 | "github.com/clancore/repo/internal/services" |
| 20 | ) |
| 21 | |
| 22 | //go:embed static templates |
| 23 | var assets embed.FS |
| 24 | |
| 25 | func main() { |
| 26 | // --- пути --- |
| 27 | reposDir := "data/repos" |
| 28 | buildsDir := "data/builds" |
| 29 | dbPath := "data/clancore.db" |
| 30 | |
| 31 | for _, dir := range []string{reposDir, buildsDir, filepath.Join(buildsDir, "work")} { |
| 32 | if err := os.MkdirAll(dir, 0755); err != nil { |
| 33 | log.Fatalf("mkdir %s: %v", dir, err) |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | // --- БД --- |
| 38 | if err := db.Init(dbPath); err != nil { |
| 39 | log.Fatalf("db init: %v", err) |
| 40 | } |
| 41 | |
| 42 | // --- сервисы --- |
| 43 | gitSvc := services.NewGitService(reposDir) |
| 44 | gitSvc.BuildsDir = buildsDir |
| 45 | buildSvc := services.NewBuildService(buildsDir, gitSvc) |
| 46 | |
| 47 | // --- templates и статика из embedded FS (бинарник самодостаточен) --- |
| 48 | tmpl := handlers.NewTemplates() |
| 49 | if err := tmpl.LoadFS(assets, "templates"); err != nil { |
| 50 | log.Fatalf("templates: %v", err) |
| 51 | } |
| 52 | |
| 53 | sub, err := fs.Sub(assets, "static") |
| 54 | if err != nil { |
| 55 | log.Fatalf("static fs: %v", err) |
| 56 | } |
| 57 | staticHandler := http.FileServer(http.FS(sub)) |
| 58 | |
| 59 | // --- app + routes --- |
| 60 | app := handlers.NewApp(tmpl, gitSvc, buildSvc, staticHandler) |
| 61 | mux := http.NewServeMux() |
| 62 | app.RegisterRoutes(mux) |
| 63 | |
| 64 | auth.StartSessionCleanup() |
| 65 | |
| 66 | addr := "0.0.0.0:5758" |
| 67 | srv := &http.Server{ |
| 68 | Addr: addr, |
| 69 | Handler: mux, |
| 70 | ReadHeaderTimeout: 10 * time.Second, |
| 71 | ReadTimeout: 30 * time.Minute, |
| 72 | WriteTimeout: 30 * time.Minute, |
| 73 | IdleTimeout: 2 * time.Minute, |
| 74 | } |
| 75 | |
| 76 | // --- graceful shutdown --- |
| 77 | stop := make(chan os.Signal, 1) |
| 78 | signal.Notify(stop, os.Interrupt, syscall.SIGTERM) |
| 79 | go func() { |
| 80 | <-stop |
| 81 | log.Println("останавливаемся…") |
| 82 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 83 | defer cancel() |
| 84 | _ = srv.Shutdown(ctx) |
| 85 | }() |
| 86 | |
| 87 | log.Printf("Clancore Repo запущен на %s (локально: http://localhost:5758)", addr) |
| 88 | if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { |
| 89 | log.Fatalf("listen: %v", err) |
| 90 | } |
| 91 | } |