From 02d777a1675d12f0965e974ae8b0e2b1265210ea Mon Sep 17 00:00:00 2001 From: GrĂ©goire DuchĂȘne Date: Tue, 4 Jan 2022 14:16:32 +0000 Subject: Move redirection logic into its own HTTP handler Also, have the non-Lambda version take flags instead of environment variables and add tests for the HTTP handler. --- resp.go | 50 ++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 38 insertions(+), 12 deletions(-) (limited to 'resp.go') diff --git a/resp.go b/resp.go index f90c486..408dcd3 100644 --- a/resp.go +++ b/resp.go @@ -4,22 +4,48 @@ package main import ( - "fmt" - "os" + "log" + "net/http" + "path" "strings" + "text/template" ) -func GetBody(pkg string) string { - dest := GetDest(os.Getenv("PREFIX"), os.Getenv("DEST"), pkg) - return fmt.Sprintf(` - +var body = template.Must(template.New("").Parse(` + go-import-redirect -`, pkg, os.Getenv("VCS"), dest) +`)) + +type bodyData struct{ Package, Repository, VCS string } + +type redirector struct{ from, to, vcs string } + +var _ http.Handler = &redirector{} + +func (h *redirector) ServeHTTP(w http.ResponseWriter, req *http.Request) { + if req.Method != http.MethodGet { + w.Header().Set("Allow", http.MethodGet) + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + + pkg := path.Join(req.Host, req.URL.Path) + if req.URL.Query().Get("go-get") != "1" { + w.Header().Set("Location", "https://pkg.go.dev/"+pkg) + w.WriteHeader(http.StatusFound) + return + } + dest := h.getRepo(pkg) + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.WriteHeader(http.StatusOK) + if err := body.Execute(w, bodyData{pkg, dest, h.vcs}); err != nil { + log.Println(err) + } } -func GetDest(srcPrefix, destPrefix, pkg string) string { - srcPrefix = strings.TrimRight(srcPrefix, "/") - destPrefix = strings.TrimRight(destPrefix, "/") - path := strings.TrimLeft(strings.TrimPrefix(pkg, srcPrefix), "/") - return destPrefix + "/" + strings.Split(path, "/")[0] +func (h *redirector) getRepo(pkg string) string { + from := strings.TrimRight(h.from, "/") + to := strings.TrimRight(h.to, "/") + path := strings.TrimLeft(strings.TrimPrefix(pkg, from), "/") + return to + "/" + strings.Split(path, "/")[0] } -- cgit v1.2.3-70-g09d2