routes/handler.go (view raw)
1package routes
2
3import (
4 "log"
5 "net/http"
6 "path/filepath"
7 "regexp"
8
9 "github.com/alexedwards/flow"
10 "github.com/sosedoff/gitkit"
11 "icyphox.sh/legit/config"
12)
13
14type depsWrapper struct {
15 actualDeps deps
16 gitsvc *gitkit.Server
17}
18
19// Checks for gitprotocol-http(5) specific query params; if found, passes
20// the request on to the git http service, else render the web frontend.
21func (dw *depsWrapper) Multiplex(w http.ResponseWriter, r *http.Request) {
22 path := flow.Param(r.Context(), "...")
23 name := flow.Param(r.Context(), "name")
24 name = filepath.Clean(name)
25 gitCommand := regexp.MustCompile(`git-(upload|receive)-pack`)
26
27 if path == "info/refs" && gitCommand.MatchString(r.URL.RawQuery) && r.Method == "GET" {
28 dw.gitsvc.ServeHTTP(w, r)
29 } else if gitCommand.MatchString(path) && r.Method == "POST" {
30 dw.gitsvc.ServeHTTP(w, r)
31 } else if r.Method == "GET" {
32 log.Println("index:", r.URL.String())
33 dw.actualDeps.RepoIndex(w, r)
34 }
35}
36
37func Handlers(c *config.Config) *flow.Mux {
38 mux := flow.New()
39 d := deps{c}
40
41 gitsvc := gitkit.New(gitkit.Config{
42 Dir: c.Repo.ScanPath,
43 AutoCreate: false,
44 })
45 if err := gitsvc.Setup(); err != nil {
46 log.Fatalf("git server: %s", err)
47 }
48
49 dw := depsWrapper{actualDeps: d, gitsvc: gitsvc}
50
51 mux.NotFound = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
52 d.Write404(w)
53 })
54
55 mux.HandleFunc("/", d.Index, "GET")
56 mux.HandleFunc("/:name", dw.Multiplex, "GET", "POST")
57 mux.HandleFunc("/:name/tree/:ref/...", d.RepoTree, "GET")
58 mux.HandleFunc("/:name/blob/:ref/...", d.FileContent, "GET")
59 mux.HandleFunc("/:name/log/:ref", d.Log, "GET")
60 mux.HandleFunc("/:name/commit/:ref", d.Diff, "GET")
61 mux.HandleFunc("/:name/refs", d.Refs, "GET")
62 mux.HandleFunc("/:name/...", dw.Multiplex, "GET", "POST")
63
64 return mux
65}