mugit/internal/handlers/handlers.go(view raw)
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 |
package handlers
import (
"html/template"
"net/http"
"path/filepath"
"strings"
"time"
"olexsmir.xyz/mugit/internal/cache"
"olexsmir.xyz/mugit/internal/config"
"olexsmir.xyz/mugit/internal/git"
"olexsmir.xyz/mugit/internal/humanize"
"olexsmir.xyz/mugit/web"
)
type handlers struct {
c *config.Config
t *template.Template
repoListCache cache.Cacher[[]repoList]
readmeCache cache.Cacher[template.HTML]
diffCache cache.Cacher[*git.NiceDiff]
}
func InitRoutes(cfg *config.Config) http.Handler {
tmpls := template.Must(template.New("").
Funcs(templateFuncs).
ParseFS(web.TemplatesFS, "*"))
h := handlers{
cfg, tmpls,
cache.NewInMemory[[]repoList](cfg.Cache.HomePage),
cache.NewInMemory[template.HTML](cfg.Cache.Readme),
cache.NewInMemory[*git.NiceDiff](cfg.Cache.Diff),
}
mux := http.NewServeMux()
mux.HandleFunc("GET /", h.indexHandler)
mux.HandleFunc("GET /index.xml", h.indexFeedHandler)
mux.HandleFunc("GET /static/{file}", h.serveStaticHandler)
mux.HandleFunc("GET /{name}", h.multiplex)
mux.HandleFunc("POST /{name}", h.multiplex)
mux.HandleFunc("GET /{name}/{rest...}", h.multiplex)
mux.HandleFunc("POST /{name}/{rest...}", h.multiplex)
mux.HandleFunc("GET /{name}/feed/{$}", h.repoFeedHandler)
mux.HandleFunc("GET /{name}/tree/{ref}/{rest...}", h.repoTreeHandler)
mux.HandleFunc("GET /{name}/blob/{ref}/{rest...}", h.fileContentsHandler)
mux.HandleFunc("GET /{name}/log/{ref}", h.logHandler)
mux.HandleFunc("GET /{name}/commit/{ref}", h.commitHandler)
mux.HandleFunc("GET /{name}/refs/{$}", h.refsHandler)
mux.HandleFunc("GET /{name}/archive/{ref}", h.archiveHandler)
handler := h.recoverMiddleware(mux)
return h.loggingMiddleware(handler)
}
func (h *handlers) serveStaticHandler(w http.ResponseWriter, r *http.Request) {
f := filepath.Clean(r.PathValue("file"))
http.ServeFileFS(w, r, web.StaticFS, f)
}
var templateFuncs = template.FuncMap{
"humanizeRelTime": func(t time.Time) string { return humanize.Time(t) },
"humanizeTime": func(t time.Time) string { return t.Format("2006-01-02 15:04:05 MST") },
"commitSummary": func(s string) string {
before, after, found := strings.Cut(s, "\n")
first := strings.TrimSuffix(before, "\r")
if !found {
return first
}
if strings.Contains(after, "\n") {
return first + "..."
}
return first
},
}
|