From e769bcd3e1ee2583366b53351ef090de2136e637 Mon Sep 17 00:00:00 2001 From: Adphi Date: Sat, 21 Nov 2020 21:45:39 +0100 Subject: [PATCH] proxy repo files --- handler.go | 38 +++++++++++++++++++++++++++++++++++++- module.go | 3 +++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/handler.go b/handler.go index dd208b1..dcb1a75 100644 --- a/handler.go +++ b/handler.go @@ -1,8 +1,14 @@ package main import ( + "bytes" + "io" "net/http" + url2 "net/url" "path" + "strings" + + "github.com/sirupsen/logrus" ) func modulesHandler(w http.ResponseWriter, r *http.Request) { @@ -19,14 +25,44 @@ func modulesHandler(w http.ResponseWriter, r *http.Request) { http.Error(w, err.Error(), http.StatusInternalServerError) } default: - m, ok := modules.Find(path.Base(r.URL.Path)) + mPath := strings.Split(r.URL.Path, "/")[1] + m, ok := modules.Find(path.Base(mPath)) if !ok { w.WriteHeader(http.StatusNotFound) return } + if parts := strings.Split(r.URL.Path, "/"); len(parts) > 2 && parts[2] != ""{ + url, err := url2.ParseRequestURI(m.Readme) + if err != nil { + logrus.Errorf("parse readme url: %v", err) + w.WriteHeader(http.StatusNotFound) + return + } + baseParts := strings.Split(url.Path, "/") + url.Path = strings.Join(baseParts[:len(baseParts)-1], "/") + "/" + strings.Join(parts[2:], "/") + res, err := http.Get(url.String()) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + return + } + w.WriteHeader(res.StatusCode) + copy(w, res) + return + } + if !strings.HasSuffix(r.URL.Path, "/") { + http.Redirect(w, r, r.URL.Path+"/", http.StatusSeeOther) + return + } w.Header().Set("content-type", "text/html") if err := moduleTemplate.Execute(w, m); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } } + +func copy(w http.ResponseWriter, res *http.Response) { + defer res.Body.Close() + buf := &bytes.Buffer{} + io.Copy(buf, res.Body) + w.Write(buf.Bytes()) +} diff --git a/module.go b/module.go index d71baf2..d01e544 100644 --- a/module.go +++ b/module.go @@ -70,6 +70,9 @@ func NewModules(path string) (Modules, error) { type Modules []*Module func (m *Modules) Find(name string) (*Module, bool) { + if parts := strings.Split(name, "/"); len(parts) > 1 { + name = parts[0] + } for _, v := range *m { mod := path.Base(v.Import) if mod == name {