cerrado @ c06945c189c1d8ef3cedeb51e416ba0fec36368f

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