gocustomurls/handlers.go

100 lines
2.1 KiB
Go

package main
import (
"bytes"
"fmt"
"net"
"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 {
e := fmt.Errorf("cannot reload rules: %+v", err)
http.Error(w, e.Error(), http.StatusInternalServerError)
return
}
w.Write([]byte("ok"))
}
}
func serveRules(c *Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var nameOfPkg string
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" {
data, err := getDefaultHtml()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(data)
return
}
ipFragments := strings.Split(r.Host, ":")
if len(ipFragments) > 1 {
ipAddr := net.ParseIP(ipFragments[0])
if ipAddr.IsLoopback() {
nameOfPkg = ipAddr.String() + r.URL.Path
}
} else {
nameOfPkg = r.Host + r.URL.Path
}
var found bool
var vanityUrl, proto, repoUrl string
for _, rule := range c.MappingRules.Mappings {
if strings.HasPrefix(strings.ToLower(rule.VanityUrl+"/"), strings.Trim(strings.ToLower(nameOfPkg), " ")) {
vanityUrl = rule.VanityUrl
repoUrl = rule.RealUrl
proto = rule.Protocol
found = true
break
}
}
if !found {
data, err := getDefaultHtml()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(data)
return
}
d := ImportRuleStruct{
VanityUrl: vanityUrl,
Proto: proto,
RepoUrl: repoUrl,
}
tmpl, err := getServeHtml()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
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())
}
}