99 lines
1.8 KiB
Go
99 lines
1.8 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"html/template"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"strings"
|
|
)
|
|
|
|
var (
|
|
giteaHost string
|
|
giteaAPIToken string
|
|
|
|
shortHost string
|
|
)
|
|
|
|
const templateHTML = `<!doctype html>
|
|
<html>
|
|
<head>
|
|
<meta name="go-import" content="{{.ShortPath}} git {{.HTTPPath}}.git">
|
|
<meta name="go-source" content="{{.ShortPath}} _ {{.HTTPPath}}/src/branch/master{/dir} {{.HTTPPath}}/src/branch/master{/dir}/{file}#L{line}">
|
|
</head>
|
|
<body>
|
|
go get {{.ShortPath}}
|
|
</body>
|
|
</html>`
|
|
|
|
type templateData struct {
|
|
ShortPath string
|
|
HTTPPath string
|
|
}
|
|
|
|
func repoExists(name string) bool {
|
|
endpoint := fmt.Sprintf("%s/api/v1/repos/%s", giteaHost, name)
|
|
|
|
client := &http.Client{}
|
|
req, _ := http.NewRequest("GET", endpoint, nil)
|
|
req.Header.Set("Authorization", "token "+giteaAPIToken)
|
|
|
|
resp, err := client.Do(req)
|
|
|
|
if err != nil {
|
|
log.Println(err)
|
|
return false
|
|
}
|
|
|
|
resp.Body.Close()
|
|
|
|
return resp.StatusCode == 200
|
|
}
|
|
|
|
func handle(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path == "/favicon.ico" {
|
|
w.WriteHeader(http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
cleanedURL := strings.Trim(r.URL.Path, "/")
|
|
|
|
if !repoExists(cleanedURL) {
|
|
w.WriteHeader(http.StatusNotFound)
|
|
fmt.Fprintf(w, ":3")
|
|
return
|
|
}
|
|
|
|
t, err := template.New("tmpl").Parse(templateHTML)
|
|
if err != nil {
|
|
log.Println(err)
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
data := templateData{
|
|
ShortPath: shortHost + "/" + cleanedURL,
|
|
HTTPPath: giteaHost + "/" + cleanedURL,
|
|
}
|
|
|
|
err = t.ExecuteTemplate(w, "tmpl", data)
|
|
if err != nil {
|
|
log.Println(err)
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
return
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
giteaHost = os.Getenv("GITEA_HOST")
|
|
giteaAPIToken = os.Getenv("GITEA_API_TOKEN")
|
|
shortHost = os.Getenv("SHORT_HOST")
|
|
|
|
httpHost := os.Getenv("HTTP_HOST")
|
|
|
|
http.HandleFunc("/", handle)
|
|
|
|
http.ListenAndServe(httpHost, nil)
|
|
}
|