gocustomurls/handlers.go

72 lines
1.6 KiB
Go

package main
import (
"bytes"
"net/http"
"strings"
)
func healthcheck(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok"))
}
func reloadRules(c *Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
err := c.LoadMappingFile("")
if err != nil {
errorLog.Printf("Cannot reload rules: %+v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write([]byte("ok"))
}
}
func serveRules(c *Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusInternalServerError)
return
}
// if go-get param is absent, return nothing
if r.FormValue("go-get") != "1" {
w.Write(GetDefaultHtml())
return
}
nameOfPkg := r.Host + r.URL.Path
var vanityUrl, proto, repoUrl string
for _, rule := range c.MappingRules.Mappings {
if strings.HasPrefix(strings.ToLower(nameOfPkg), strings.ToLower(rule.VanityUrl+"/")) {
repo := strings.Replace(strings.ToLower(nameOfPkg), strings.ToLower(rule.VanityUrl), "", -1)
repo = strings.Split(repo, "/")[1]
vanityUrl = rule.VanityUrl + "/" + repo
repoUrl = rule.RealUrl + "/" + repo
proto = rule.Protocol
break
}
}
d := ImportRuleStruct{
VanityUrl: vanityUrl,
Proto: proto,
RepoUrl: repoUrl,
}
tmpl := GetServeHtml()
var buf bytes.Buffer
err := tmpl.Execute(&buf, &d)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Cache-Control", "public, max-age=500")
w.Write(buf.Bytes())
}
}