main / internal/interface/web/router.go
2.7 KB · Go Raw
1package web
2
3import (
4 "embed"
5 "net/http"
6
7 "github.com/a-h/templ"
8 "github.com/go-chi/chi"
9 "github.com/go-chi/chi/middleware"
10
11 "gitgud/internal/infra/config"
12)
13
14var staticFS embed.FS
15
16func NewRouter(cfg config.Config, h *Handlers) http.Handler {
17 r := chi.NewRouter()
18
19 r.Use(middleware.Logger, middleware.Recoverer)
20 r.Use(h.sm.LoadAndSave)
21 r.Use(csrf)
22 r.Use(h.withFlash)
23 r.Use(h.withUser)
24
25 r.Get("/health", func(w http.ResponseWriter, r *http.Request) {
26 w.WriteHeader(http.StatusOK)
27 w.Write([]byte("OK"))
28 })
29 r.Handle("/static/*", http.StripPrefix("/static", http.FileServer((http.FS(staticFS)))))
30
31 r.Get("/register", h.showRegister)
32 r.Post("/register", h.doRegister)
33 r.Get("/login", h.showLogin)
34 r.Post("/login", h.doLogin)
35 r.Post("/logout", h.doLogout)
36
37 r.With(h.requireAuth).Get("/new", h.showNewRepo)
38 r.With(h.requireAuth).Post("/new", h.createRepo)
39
40 r.Get("/{owner}/{repo}/info/refs", h.gitHTTP)
41 r.Post("/{owner}/{repo}/git-upload-pack", h.gitHTTP)
42 r.Post("/{owner}/{repo}/git-receive-pack", h.gitHTTP)
43
44 r.Get("/", h.explore)
45 r.Get("/{owner}", h.profile)
46 r.Get("/{owner}/{repo}", h.repoTreeRoot)
47 r.Get("/{owner}/{repo}/tree/{ref}", h.repoTree)
48 r.Get("/{owner}/{repo}/tree/{ref}/*", h.repoTree)
49 r.Get("/{owner}/{repo}/blob/{ref}/*", h.repoBlob)
50 r.Get("/{owner}/{repo}/raw/{ref}/*", h.repoRaw)
51 r.Get("/{owner}/{repo}/commits/{ref}", h.repoCommits)
52 r.Get("/{owner}/{repo}/commit/{hash}", h.repoCommit)
53
54 r.Get("/{owner}/{repo}/issues", h.issuesList)
55 r.With(h.requireAuth).Get("/{owner}/{repo}/issues/new", h.newIssue)
56 r.With(h.requireAuth).Post("/{owner}/{repo}/issues", h.createIssue)
57 r.Get("/{owner}/{repo}/issues/{number}", h.issueDetail)
58 r.With(h.requireAuth).Post("/{owner}/{repo}/issues/{number}/comments", h.addIssueComment)
59 r.With(h.requireAuth).Post("/{owner}/{repo}/issues/{number}/close", h.closeIssue)
60 r.With(h.requireAuth).Post("/{owner}/{repo}/issues/{number}/reopen", h.reopenIssue)
61
62 r.Get("/{owner}/{repo}/pulls", h.pullsList)
63 r.Get("/{owner}/{repo}/compare", h.comparePull)
64 r.With(h.requireAuth).Get("/{owner}/{repo}/pulls/new", h.comparePull)
65 r.With(h.requireAuth).Post("/{owner}/{repo}/pulls", h.createPull)
66 r.Get("/{owner}/{repo}/pulls/{number}", h.pullDetail)
67 r.With(h.requireAuth).Post("/{owner}/{repo}/pulls/{number}/comments", h.addPullComment)
68 r.With(h.requireAuth).Post("/{owner}/{repo}/pulls/{number}/merge", h.mergePull)
69 r.With(h.requireAuth).Post("/{owner}/{repo}/pulls/{number}/close", h.closePull)
70
71 return r
72}
73
74func render(w http.ResponseWriter, r *http.Request, status int, c templ.Component) {
75 w.Header().Set("Content-Type", "text/html; charset=utf-8")
76 w.WriteHeader(status)
77 if err := c.Render(r.Context(), w); err != nil {
78 http.Error(w, err.Error(), http.StatusInternalServerError)
79 }
80}