DEVELOPMENT ENVIRONMENT

~liljamo/felu

ref: 08a7a55902c758aaf1432ce557f0143715c363ee felu/cmd/felu/main.go -rw-r--r-- 2.2 KiB
08a7a559Jonni Liljamo feat: tsig 17 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
 * Copyright (C) 2024 Jonni Liljamo <jonni@liljamo.com>
 *
 * This file is licensed under AGPL-3.0-or-later, see NOTICE and LICENSE for
 * more information.
 */

// nolint
package main

import (
	"log/slog"
	"net/http"
	"os"
	"strconv"
	"time"

	"git.src.quest/~liljamo/felu/internal/config"
	"git.src.quest/~liljamo/felu/internal/db"
	"git.src.quest/~liljamo/felu/internal/dns"
	"git.src.quest/~liljamo/felu/internal/log"
	"git.src.quest/~liljamo/felu/internal/routers"
	"github.com/alexedwards/scs/v2"
	"golang.org/x/sync/errgroup"
)

var version = "notset-builtin"

var (
	g              errgroup.Group
	sessionManager *scs.SessionManager
)

func main() {
	config.InitConfig()

	log.InitDefaultLogger(config.FeluConfig.LogLevel)
	slog.Info("Starting up...")

	if err := db.InitDB(); err != nil {
		slog.Error("Failed to initialize database", slog.Any("err", err))
		os.Exit(1)
	}
	defer db.DBConn.Close()
	if err := db.InitAdminUser(); err != nil {
		slog.Error("Failed to initialize admin user", slog.Any("err", err))
		os.Exit(1)
	}

	sessionManager = scs.New()
	sessionManager.Lifetime = 6 * time.Hour

	frontend := &http.Server{
		Addr:         config.FeluConfig.FrontendBindAddr,
		Handler:      sessionManager.LoadAndSave(routers.SetupFrontendRouter(sessionManager)),
		ReadTimeout:  5 * time.Second,
		WriteTimeout: 10 * time.Second,
	}

	api := &http.Server{
		Addr:         config.FeluConfig.APIBindAddr,
		Handler:      routers.SetupAPIRouter(version),
		ReadTimeout:  5 * time.Second,
		WriteTimeout: 10 * time.Second,
	}

	slog.Info("Serving frontend", slog.String("addr", config.FeluConfig.FrontendBindAddr))
	g.Go(func() error {
		return frontend.ListenAndServe()
	})

	slog.Info("Serving API", slog.String("addr", config.FeluConfig.APIBindAddr))
	g.Go(func() error {
		return api.ListenAndServe()
	})

	dnsIP := config.FeluConfig.DNSBindIP
	dnsPort := strconv.Itoa(int(config.FeluConfig.DNSBindPort))
	dnsAddr := dnsIP + ":" + dnsPort
	slog.Info("Serving DNS (udp)", slog.String("addr", dnsAddr))
	g.Go(func() error {
		return dns.Run(dnsAddr, "udp")
	})
	slog.Info("Serving DNS (tcp)", slog.String("addr", dnsAddr))
	g.Go(func() error {
		return dns.Run(dnsAddr, "tcp")
	})

	if err := g.Wait(); err != nil {
		slog.Info("Error while running", slog.Any("err", err))
	}
}