mugit/internal/handlers/handlers.go (view raw)
Oleksandr Smirnov
Oleksandr Smirnov
olexsmir@gmail.com support both repo and repo.git as names, 4 months ago
olexsmir@gmail.com support both repo and repo.git as names, 4 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 | |
| 39 | handler := h.recoverMiddleware(mux) |
| 40 | return h.loggingMiddleware(handler) |
| 41 | } |
| 42 | |
| 43 | func (h *handlers) serveStatic(w http.ResponseWriter, r *http.Request) { |
| 44 | f := filepath.Clean(r.PathValue("file")) |
| 45 | // TODO: check if files exists |
| 46 | http.ServeFileFS(w, r, web.StaticFS, f) |
| 47 | } |
| 48 | |
| 49 | func repoNameToPath(name string) string { return name + ".git" } |
| 50 | func getNormalizedName(name string) string { |
| 51 | return strings.TrimSuffix(name, ".git") |
| 52 | } |
| 53 | |
| 54 | var templateFuncs = template.FuncMap{ |
| 55 | "humanizeTime": func(t time.Time) string { return humanize.Time(t) }, |
| 56 | "commitSummary": func(s string) string { |
| 57 | before, after, found := strings.Cut(s, "\n") |
| 58 | first := strings.TrimSuffix(before, "\r") |
| 59 | if !found { |
| 60 | return first |
| 61 | } |
| 62 | |
| 63 | if strings.Contains(after, "\n") { |
| 64 | return first + "..." |
| 65 | } |
| 66 | |
| 67 | return first |
| 68 | }, |
| 69 | } |