repos / git-pr

a self-hosted git collaboration server
git clone https://github.com/picosh/git-pr.git

commit
7c6fe3b
parent
32f04ff
author
Eric Bower
date
2024-05-19 18:56:20 -0400 EDT
web server
4 files changed,  +97, -1
A web.go
M Makefile
+2, -1
1@@ -8,5 +8,6 @@ lint:
2 .PHONY: lint
3 
4 build:
5-	go build -o ./build/git ./cmd/git
6+	go build -o ./build/ssh ./cmd/ssh
7+	go build -o ./build/web ./cmd/web
8 .PHONY: build
R cmd/git/main.go => cmd/ssh/main.go
+0, -0
A cmd/web/main.go
+7, -0
1@@ -0,0 +1,7 @@
2+package main
3+
4+import git "github.com/picosh/pico-git"
5+
6+func main() {
7+	git.StartWebServer()
8+}
A web.go
+88, -0
 1@@ -0,0 +1,88 @@
 2+package git
 3+
 4+import (
 5+	"context"
 6+	"fmt"
 7+	"log/slog"
 8+	"net/http"
 9+	"os"
10+)
11+
12+type ctxPr struct{}
13+
14+func getPrCtx(r *http.Request) (*PrCmd, error) {
15+	pr, ok := r.Context().Value(ctxPr{}).(*PrCmd)
16+	if pr == nil || !ok {
17+		return pr, fmt.Errorf("pr not set on `r.Context()` for connection")
18+	}
19+	return pr, nil
20+}
21+func setPrCtx(ctx context.Context, pr *PrCmd) context.Context {
22+	return context.WithValue(ctx, ctxPr{}, pr)
23+}
24+
25+func ctxMdw(ctx context.Context, handler http.HandlerFunc) http.HandlerFunc {
26+	return func(w http.ResponseWriter, r *http.Request) {
27+		handler(w, r.WithContext(ctx))
28+	}
29+}
30+
31+func prHandler(w http.ResponseWriter, r *http.Request) {
32+	pr, err := getPrCtx(r)
33+	if err != nil {
34+		fmt.Println(err)
35+		w.WriteHeader(http.StatusInternalServerError)
36+		return
37+	}
38+
39+	str := "Patch Requests\n"
40+	prs, err := pr.GetPatchRequests()
41+	if err != nil {
42+		pr.Backend.Logger.Error("cannot get prs", "err", err)
43+		w.WriteHeader(http.StatusInternalServerError)
44+		return
45+	}
46+
47+	for _, curpr := range prs {
48+		str += fmt.Sprintf("%d\t%s\t%s\t%s\n", curpr.ID, curpr.RepoID, curpr.Name, curpr.Pubkey)
49+	}
50+	fmt.Fprintf(w, str)
51+}
52+
53+func StartWebServer() {
54+	host := os.Getenv("WEB_HOST")
55+	if host == "" {
56+		host = "0.0.0.0"
57+	}
58+	port := os.Getenv("WEB_PORT")
59+	if port == "" {
60+		port = "3000"
61+	}
62+	addr := fmt.Sprintf("%s:%s", host, port)
63+	logger := slog.Default()
64+
65+	dbh, err := Open("./test.db", logger)
66+	if err != nil {
67+		logger.Error("could not open db", "err", err)
68+		return
69+	}
70+
71+	be := &Backend{
72+		DB:     dbh,
73+		Logger: logger,
74+	}
75+	prCmd := &PrCmd{
76+		Backend: be,
77+	}
78+	ctx := context.Background()
79+	ctx = setPrCtx(ctx, prCmd)
80+
81+	mux := http.NewServeMux()
82+	mux.HandleFunc("/", ctxMdw(ctx, prHandler))
83+
84+	logger.Info("starting web server", "addr", addr)
85+	err = http.ListenAndServe(addr, mux)
86+	if err != nil {
87+		logger.Error("listen", "err", err)
88+	}
89+}