Files
neural-hunt/cmd/server/main.go
jbergner 005fd6ca51
Some checks failed
release-tag / release-image (push) Failing after 1m18s
RC-1
2026-08-10 05:48:55 +02:00

110 lines
2.3 KiB
Go

package main
import (
"bufio"
"context"
"log"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"neuralhunt/internal/artifact"
"neuralhunt/internal/auth"
"neuralhunt/internal/data"
rtx "neuralhunt/internal/runtime"
"neuralhunt/internal/server"
"neuralhunt/internal/settings"
wsx "neuralhunt/internal/ws"
)
func env(k, d string) string {
if v := os.Getenv(k); v != "" {
return v
}
return d
}
func loadDotEnv(path string) {
f, err := os.Open(path)
if err != nil {
return
}
defer f.Close()
s := bufio.NewScanner(f)
for s.Scan() {
line := strings.TrimSpace(s.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
if strings.HasPrefix(line, "export ") {
line = strings.TrimSpace(strings.TrimPrefix(line, "export "))
}
k, v, ok := strings.Cut(line, "=")
if !ok {
continue
}
k = strings.TrimSpace(k)
if k == "" {
continue
}
if _, exists := os.LookupEnv(k); exists {
continue
}
v = strings.TrimSpace(v)
if len(v) >= 2 && ((v[0] == '"' && v[len(v)-1] == '"') || (v[0] == '\'' && v[len(v)-1] == '\'')) {
v = v[1 : len(v)-1]
}
_ = os.Setenv(k, v)
}
}
func main() {
loadDotEnv(".env")
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer cancel()
db, err := data.OpenSQLite(ctx, env("SQLITE_PATH", "./data/neuralhunt.db"))
if err != nil {
log.Fatal(err)
}
defer db.Close()
sm, err := settings.New(ctx, db)
if err != nil {
log.Fatal(err)
}
go sm.Run(ctx)
store := data.New(db)
a := auth.New(db, env("JWT_SECRET", "dev-secret-change-me"))
hub := wsx.New()
runtimeState := rtx.New()
go hub.Run(ctx)
artifactDir := env("ARTIFACT_DIR", "./data/artifacts")
aw, err := artifact.New(db, artifactDir, sm)
if err != nil {
log.Fatal(err)
}
go aw.Run(ctx)
srv := server.New(store, a, sm, hub, runtimeState, artifactDir, aw)
go srv.Scheduler(ctx)
httpSrv := &http.Server{Addr: env("HTTP_ADDR", ":8080"), Handler: srv.Routes(), ReadHeaderTimeout: 5 * time.Second}
go func() {
log.Printf("listening on %s", httpSrv.Addr)
if err := httpSrv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatal(err)
}
}()
<-ctx.Done()
shutdown, done := context.WithTimeout(context.Background(), 10*time.Second)
defer done()
_ = httpSrv.Shutdown(shutdown)
}