all repos

mugit @ 96b3828

🐮 git server that your cow will love

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

Oleksandr Smirnov Oleksandr Smirnov
olexsmir@gmail.com
git: resolve name and paths, 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 /index.xml", h.indexFeedHandler)
29
	mux.HandleFunc("GET /static/{file}", h.serveStaticHandler)
30
	mux.HandleFunc("GET /{name}", h.multiplex)
31
	mux.HandleFunc("POST /{name}", h.multiplex)
32
	mux.HandleFunc("GET /{name}/{rest...}", h.multiplex)
33
	mux.HandleFunc("POST /{name}/{rest...}", h.multiplex)
34
	mux.HandleFunc("GET /{name}/feed/{$}", h.repoFeedHandler)
35
	mux.HandleFunc("GET /{name}/tree/{ref}/{rest...}", h.repoTreeHandler)
36
	mux.HandleFunc("GET /{name}/blob/{ref}/{rest...}", h.fileContentsHandler)
37
	mux.HandleFunc("GET /{name}/log/{ref}", h.logHandler)
38
	mux.HandleFunc("GET /{name}/commit/{ref}", h.commitHandler)
39
	mux.HandleFunc("GET /{name}/refs/{$}", h.refsHandler)
40
	mux.HandleFunc("GET /{name}/archive/{ref}", h.archiveHandler)
41
42
	handler := h.recoverMiddleware(mux)
43
	return h.loggingMiddleware(handler)
44
}
45
46
func (h *handlers) serveStaticHandler(w http.ResponseWriter, r *http.Request) {
47
	f := filepath.Clean(r.PathValue("file"))
48
	http.ServeFileFS(w, r, web.StaticFS, f)
49
}
50
51
var templateFuncs = template.FuncMap{
52
	"humanizeTime": func(t time.Time) string { return humanize.Time(t) },
53
	"commitSummary": func(s string) string {
54
		before, after, found := strings.Cut(s, "\n")
55
		first := strings.TrimSuffix(before, "\r")
56
		if !found {
57
			return first
58
		}
59
60
		if strings.Contains(after, "\n") {
61
			return first + "..."
62
		}
63
64
		return first
65
	},
66
}