summaryrefslogtreecommitdiff
path: root/main.go
blob: 49abeb827bb73d0b9b1824fea7a5796f60dbc0dc (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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main

import (
	"context"
	"encoding/json"
	"html/template"
	"log/slog"
	"net/http"
	"os"
	"os/signal"

	"gitrepo.ru/neonxp/middleware"
)

var (
	templates = template.Must(template.ParseFS(tplFS, "tpl/*.gohtml"))
	packages  = Packages{}
)

func main() {
	addr := os.Getenv("ADDR")
	if addr == "" {
		addr = ":8080"
	}
	ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, os.Kill)
	defer cancel()

	cfg := &Config{}

	fp, err := os.Open("./config.json")
	if err != nil {
		panic(err)
	}
	if err := json.NewDecoder(fp).Decode(cfg); err != nil {
		panic(err)
	}

	mux := http.NewServeMux()

	mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		templates.ExecuteTemplate(w, "index.gohtml", indexRenderContext{
			Title:    cfg.Title,
			Packages: cfg.Packages,
			Host:     cfg.Host,
			Doc:      "//pkg.go.dev/",
		})
	})

	mux.HandleFunc("GET /{pkg}", func(w http.ResponseWriter, r *http.Request) {
		pkgID := r.PathValue("pkg")
		pkg, ok := (*cfg.Packages)[pkgID]
		if !ok {
			w.WriteHeader(http.StatusNotFound)
			return
		}
		w.WriteHeader(http.StatusOK)
		templates.ExecuteTemplate(w, "package.gohtml", pageRenderContext{
			Title:   cfg.Title,
			Package: &pkg,
			Host:    cfg.Host,
			Doc:     "//pkg.go.dev/",
		})
	})
	mux.Handle("GET /static/", http.FileServerFS(staticFS))

	logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{}))
	h := middleware.Use(mux,
		middleware.Logger(logger),
		middleware.Recover(logger),
		middleware.RequestID,
	)

	srv := &http.Server{
		Handler: h,
		Addr:    addr,
	}
	go func() {
		<-ctx.Done()
		srv.Shutdown(context.Background())
	}()

	logger.Info("server started", slog.String("bind", addr))
	if err := srv.ListenAndServe(); err != http.ErrServerClosed {
		panic(err)
	}
}