all repos

mugit @ e1d1a9eda5d5e5aacfe4a2f899f9f65ba5b772d5

🐮 git server that your cow will love

mugit/internal/handlers/handlers.go (view raw)

Oleksandr Smirnov Oleksandr Smirnov
olexsmir@gmail.com
git: archive, 3 months ago
1
package handlers
2
3
import (
4
	"html/template"
5
	"net/http"
6
	"path/filepath"
7
	"strings"
8
	"time"
9
10
	"olexsmir.xyz/mugit/internal/config"
11
	"olexsmir.xyz/mugit/internal/humanize"
12
	"olexsmir.xyz/mugit/web"
13
)
14
15
type handlers struct {
16
	c *config.Config
17
	t *template.Template
18
}
19
20
func InitRoutes(cfg *config.Config) http.Handler {
21
	tmpls := template.Must(template.New("").
22
		Funcs(templateFuncs).
23
		ParseFS(web.TemplatesFS, "*"))
24
	h := handlers{cfg, tmpls}
25
26
	mux := http.NewServeMux()
27
	mux.HandleFunc("GET /", h.indexHandler)
28
	mux.HandleFunc("GET /static/{file}", h.serveStatic)
29
	mux.HandleFunc("GET /{name}", h.multiplex)
30
	mux.HandleFunc("POST /{name}", h.multiplex)
31
	mux.HandleFunc("GET /{name}/{rest...}", h.multiplex)
32
	mux.HandleFunc("POST /{name}/{rest...}", h.multiplex)
33
	mux.HandleFunc("GET /{name}/tree/{ref}/{rest...}", h.repoTreeHandler)
34
	mux.HandleFunc("GET /{name}/blob/{ref}/{rest...}", h.fileContentsHandler)
35
	mux.HandleFunc("GET /{name}/log/{ref}", h.logHandler)
36
	mux.HandleFunc("GET /{name}/commit/{ref}", h.commitHandler)
37
	mux.HandleFunc("GET /{name}/refs/{$}", h.refsHandler)
38
	mux.HandleFunc("GET /{name}/archive/{ref}", h.archiveHandler)
39
40
41
	handler := h.recoverMiddleware(mux)
42
	return h.loggingMiddleware(handler)
43
}
44
45
func (h *handlers) serveStatic(w http.ResponseWriter, r *http.Request) {
46
	f := filepath.Clean(r.PathValue("file"))
47
	// TODO: check if files exists
48
	http.ServeFileFS(w, r, web.StaticFS, f)
49
}
50
51
func repoNameToPath(name string) string { return name + ".git" }
52
func getNormalizedName(name string) string {
53
	return strings.TrimSuffix(name, ".git")
54
}
55
56
var templateFuncs = template.FuncMap{
57
	"humanizeTime": func(t time.Time) string { return humanize.Time(t) },
58
	"commitSummary": func(s string) string {
59
		before, after, found := strings.Cut(s, "\n")
60
		first := strings.TrimSuffix(before, "\r")
61
		if !found {
62
			return first
63
		}
64
65
		if strings.Contains(after, "\n") {
66
			return first + "..."
67
		}
68
69
		return first
70
	},
71
}