1package web
 2
 3import (
 4	"net/http"
 5	"net/url"
 6	"path"
 7	"text/template"
 8
 9	"github.com/charmbracelet/soft-serve/server/backend"
10	"github.com/charmbracelet/soft-serve/server/config"
11	"github.com/charmbracelet/soft-serve/server/utils"
12	"github.com/prometheus/client_golang/prometheus"
13	"github.com/prometheus/client_golang/prometheus/promauto"
14	"goji.io/pattern"
15)
16
17var goGetCounter = promauto.NewCounterVec(prometheus.CounterOpts{
18	Namespace: "soft_serve",
19	Subsystem: "http",
20	Name:      "go_get_total",
21	Help:      "The total number of go get requests",
22}, []string{"repo"})
23
24var repoIndexHTMLTpl = template.Must(template.New("index").Parse(`<!DOCTYPE html>
25<html lang="en">
26<head>
27    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
28    <meta http-equiv="refresh" content="0; url=https://godoc.org/{{ .ImportRoot }}/{{.Repo}}">
29    <meta name="go-import" content="{{ .ImportRoot }}/{{ .Repo }} git {{ .Config.HTTP.PublicURL }}/{{ .Repo }}">
30</head>
31<body>
32Redirecting to docs at <a href="https://godoc.org/{{ .ImportRoot }}/{{ .Repo }}">godoc.org/{{ .ImportRoot }}/{{ .Repo }}</a>...
33</body>
34</html>`))
35
36// GoGetHandler handles go get requests.
37type GoGetHandler struct{}
38
39var _ http.Handler = (*GoGetHandler)(nil)
40
41func (g GoGetHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
42	repo := pattern.Path(r.Context())
43	repo = utils.SanitizeRepo(repo)
44	ctx := r.Context()
45	cfg := config.FromContext(ctx)
46	be := backend.FromContext(ctx)
47
48	// Handle go get requests.
49	//
50	// Always return a 200 status code, even if the repo doesn't exist.
51	//
52	// https://golang.org/cmd/go/#hdr-Remote_import_paths
53	// https://go.dev/ref/mod#vcs-branch
54	if r.URL.Query().Get("go-get") == "1" {
55		repo := repo
56		importRoot, err := url.Parse(cfg.HTTP.PublicURL)
57		if err != nil {
58			http.Error(w, err.Error(), http.StatusInternalServerError)
59			return
60		}
61
62		// find the repo
63		for {
64			if _, err := be.Repository(ctx, repo); err == nil {
65				break
66			}
67
68			if repo == "" || repo == "." || repo == "/" {
69				return
70			}
71
72			repo = path.Dir(repo)
73		}
74
75		if err := repoIndexHTMLTpl.Execute(w, struct {
76			Repo       string
77			Config     *config.Config
78			ImportRoot string
79		}{
80			Repo:       url.PathEscape(repo),
81			Config:     cfg,
82			ImportRoot: importRoot.Host,
83		}); err != nil {
84			http.Error(w, err.Error(), http.StatusInternalServerError)
85			return
86		}
87
88		goGetCounter.WithLabelValues(repo).Inc()
89		return
90	}
91
92	http.NotFound(w, r)
93}