This repository has been archived by the owner on Nov 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
111 lines (94 loc) · 2.42 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package main
import (
"bytes"
"fmt"
"html/template"
"log"
"net/http"
"net/url"
"os"
"path"
)
const (
envVanityVCS = "VANITY_VCS"
envVanityVCSURL = "VANITY_VCS_URL"
)
func main() {
// check for VCS type
vcs := os.Getenv(envVanityVCS)
if vcs == "" {
vcs = "git"
}
// check for VCS URL
vcsURL := os.Getenv(envVanityVCSURL)
if vcsURL == "" {
log.Fatalf("%s must be set, e.g. https://github.com/username", envVanityVCSURL)
}
// attempt to parse VCS URL
u, err := url.Parse(vcsURL)
if err != nil {
log.Fatalf("invalid VCS URL: %v", err)
}
// check for HTTPS
if u.Scheme != "https" {
log.Fatalf("%s scheme must be HTTPS", envVanityVCSURL)
}
// configure health check
http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Write([]byte("ok"))
})
// configure root handler
http.HandleFunc("/", handler(vcs, u))
// start web server
log.Printf("starting web server on :8080, VCS: %s, VCS_URL: %s", vcs, vcsURL)
log.Fatal(http.ListenAndServe(":8080", nil))
}
var tmpl = template.Must(template.New("html").Parse(`<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="go-import" content="{{.Host}} {{.VCS}} {{.VCSURL}}">
</head>
</html>
`))
func handler(vcs string, vcsURL *url.URL) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.URL.Scheme != "https" {
proto := r.Header.Get("X-Forwarded-Proto")
if proto == "" || proto != "https" {
http.Redirect(w, r, fmt.Sprintf("https://%s%s", r.Host, r.URL.RequestURI()), http.StatusMovedPermanently)
return
}
}
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
u, err := url.Parse(fmt.Sprintf("https://%s%s", vcsURL.Host, path.Join(vcsURL.Path, r.URL.Path)))
if err != nil {
http.Error(w, fmt.Sprintf("error building VCS URL: %v", err), http.StatusInternalServerError)
return
}
if r.URL.Query().Get("go-get") != "1" || len(r.URL.Path) < 2 {
http.Redirect(w, r, u.String(), http.StatusTemporaryRedirect)
return
}
data := struct {
Host string
VCS string
VCSURL string
}{
path.Join(r.Host, r.URL.Path),
vcs,
u.String(),
}
var buf bytes.Buffer
if err := tmpl.Execute(&buf, &data); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Cache-Control", "no-store")
w.Write(buf.Bytes())
}
}