cerrado @ 3be25766027178489a0c5f1f82e65f9be518c79c

 1package main
 2
 3import (
 4	"bytes"
 5	"context"
 6	"encoding/json"
 7	"flag"
 8	"log/slog"
 9	"net/http"
10	"os"
11	"os/signal"
12	"time"
13
14	"github.com/alecthomas/chroma/v2/formatters/html"
15	"github.com/alecthomas/chroma/v2/lexers"
16	"github.com/alecthomas/chroma/v2/styles"
17
18	"git.gabrielgio.me/cerrado/pkg/config"
19	"git.gabrielgio.me/cerrado/pkg/worker"
20	"git.gabrielgio.me/cerrado/templates"
21)
22
23func main() {
24
25	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, os.Kill)
26	defer stop()
27	if err := run(ctx); err != nil {
28		os.Exit(1)
29	}
30}
31
32func run(ctx context.Context) error {
33	var (
34		configPath = flag.String("config", "config.example.scfg", "File path for the configuration file")
35	)
36
37	flag.Parse()
38
39	mux := http.NewServeMux()
40	mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {
41		slog.Info("Handling index")
42
43		f, err := os.Open(*configPath)
44		if err != nil {
45			slog.Error("Error openning config file json", "error", err, "path", *configPath)
46			return
47		}
48
49		c, err := config.Parse(f)
50		if err != nil {
51			slog.Error("Error parsing config", "error", err, "path", *configPath)
52			return
53		}
54
55		b, err := json.MarshalIndent(c, "", "	")
56		if err != nil {
57			slog.Error("Error parsing json", "error", err)
58			return
59		}
60
61		lexer := lexers.Get("json")
62		style := styles.Get("monokailight")
63		formatter := html.New(
64			html.WithLineNumbers(true),
65		)
66		iterator, err := lexer.Tokenise(nil, string(b))
67		if err != nil {
68			slog.Error("Error tokenise", "error", err)
69			return
70		}
71
72		var code bytes.Buffer
73		err = formatter.Format(&code, style, iterator)
74		if err != nil {
75			slog.Error("Error format", "error", err)
76			return
77		}
78
79		hello := &templates.HelloPage{
80			Body: code.String(),
81		}
82
83		templates.WritePageTemplate(w, hello)
84	})
85	serverTask := worker.NewServerTask(&http.Server{Handler: mux, Addr: "0.0.0.0:8080"})
86
87	pool := worker.NewTaskPool()
88	pool.AddTask("http-server", 5*time.Second, serverTask)
89
90	return pool.Start(ctx)
91}