summaryrefslogtreecommitdiffstats
path: root/main.go
blob: 3fe90015e7062f42c0c57e82f4397580d758b6b4 (plain) (blame)
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
package gopkgserver

import (
	"context"
	_ "embed"
	"flag"
	"fmt"

	"log/slog"
	"net/http"
	"os"

	"github.com/pelletier/go-toml/v2"
	"go.sudomsg.com/gopkgserver/repo"
	httpServer "go.sudomsg.com/kit/http"
	"go.sudomsg.com/kit/logging"
	logHandler "go.sudomsg.com/kit/logging/http"
)

type Config struct {
	Server  []httpServer.ServerConfig `toml:"server"`
	Logging logging.LogConfig         `toml:"logging"`
	Repos   map[string]repo.Repo      `toml:"repo"`
}

func Run(ctx context.Context, fs *flag.FlagSet, args []string) error {
	var cfgFile string
	fs.StringVar(&cfgFile, "config", "config.toml", "Path to config file")
	fs.Parse(args)

	cfg, err := LoadConfig(cfgFile)
	if err != nil {
		return err
	}

	if err := logging.Setup(cfg.Logging); err != nil {
		return err
	}
	ctx = logging.WithLogger(ctx, slog.Default())

	h, err := repo.New(cfg.Repos)
	if err != nil {
		return fmt.Errorf(": %v", err)
	}

	mux := http.NewServeMux()
	mux.Handle("GET /robots.txt", Robot())
	mux.Handle("GET /", h)

	handler := logHandler.New(mux, nil)

	lns, err := httpServer.OpenListeners(ctx, cfg.Server)
	defer lns.CloseAll()

	return httpServer.RunHTTPServers(ctx, lns, handler)
}

func LoadConfig(cfgFile string) (Config, error) {
	data, err := os.ReadFile(cfgFile)
	if err != nil {
		return Config{}, fmt.Errorf("read config: %w", err)
	}

	var cfg Config
	if err := toml.Unmarshal(data, &cfg); err != nil {
		return Config{}, fmt.Errorf("parse config: %w", err)
	}

	return cfg, nil
}