summaryrefslogtreecommitdiff
path: root/cmd/serve/main.go
blob: 9ce15cd3d9aa0a39319ea5450b78ba95ec80e202 (plain)
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
package main

import (
	"log"
	"net/http"
	"path/filepath"
	"strings"
	"time"

	"git.sr.ht/~a73x/home/public"
	"go.uber.org/zap"
)

func main() {
	if err := Run(); err != nil {
		log.Fatal(err)
	}
}

func Run() error {
	logger, err := zap.NewProduction()
	if err != nil {
		return err
	}

	loggingMiddleware := func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			start := time.Now()
			next.ServeHTTP(w, r)
			logger.Info("request received",
				zap.String("url", r.URL.Path),
				zap.String("method", r.Method),
				zap.Duration("duration", time.Since(start)),
				zap.String("user-agent", r.UserAgent()),
			)
		})
	}

	mux := http.NewServeMux()

	mux.HandleFunc("GET /", serveFile)

	server := http.Server{
		Addr:    ":8080",
		Handler: loggingMiddleware(mux),
	}

	return server.ListenAndServe()
}

func serveFile(w http.ResponseWriter, r *http.Request) {
	fsPath := strings.TrimRight(r.URL.Path, "/")

	if fsPath == "" {
		fsPath = "index"
	}

	if ext := filepath.Ext(fsPath); ext == "" {
		fsPath += ".html"
	}

	http.ServeFileFS(w, r, public.FS, fsPath)
}