go-repo/handler.go

68 lines
1.6 KiB
Go
Raw Permalink Normal View History

2020-11-21 11:01:43 +00:00
package main
import (
2020-11-21 20:45:39 +00:00
"bytes"
"io"
2020-11-21 11:01:43 +00:00
"net/http"
2020-11-21 20:45:39 +00:00
url2 "net/url"
2020-11-21 11:01:43 +00:00
"path"
2020-11-21 20:45:39 +00:00
"strings"
"github.com/sirupsen/logrus"
2020-11-21 11:01:43 +00:00
)
func modulesHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.Header().Set("content-type", "text/html")
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
mu.RLock()
defer mu.RUnlock()
switch r.URL.Path {
case "/":
if err := indexTemplate.Execute(w, modules); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
default:
2020-12-30 16:12:58 +00:00
m, ok := modules.Find(r.URL.Path)
2020-11-21 11:01:43 +00:00
if !ok {
w.WriteHeader(http.StatusNotFound)
return
}
2020-12-30 16:12:58 +00:00
if rest := strings.TrimPrefix(r.URL.Path, m.name()); strings.TrimSuffix(rest, "/") != "" {
2020-11-21 20:45:39 +00:00
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, "/")
2020-12-30 16:12:58 +00:00
url.Path = path.Join(append(baseParts[:len(baseParts)-1], rest)...)
2020-11-21 20:45:39 +00:00
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
}
2020-11-21 11:01:43 +00:00
w.Header().Set("content-type", "text/html")
if err := moduleTemplate.Execute(w, m); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
}
2020-11-21 20:45:39 +00:00
func copy(w http.ResponseWriter, res *http.Response) {
defer res.Body.Close()
buf := &bytes.Buffer{}
io.Copy(buf, res.Body)
w.Write(buf.Bytes())
}