-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvanity.go
More file actions
108 lines (92 loc) · 2.28 KB
/
vanity.go
File metadata and controls
108 lines (92 loc) · 2.28 KB
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
package main
import (
"bytes"
"fmt"
"html/template"
"log"
"net/http"
"net/url"
"os"
"path"
)
var tpl = 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}} {{.URL}}">
</head>
</html>
`))
func main() {
addr := os.Getenv("ADDR")
if addr == "" {
addr = ":8080"
}
vcs := os.Getenv("VCS")
if vcs == "" {
vcs = "git"
}
vcsURL := os.Getenv("VCS_URL")
if vcs == "" {
log.Fatal("VCS_URL env not specified (eg: https://github.com/username)")
}
u, err := url.Parse(vcsURL)
if err != nil {
log.Fatalf("invalid vcs url: %v", err)
}
if u.Scheme != "https" {
log.Fatalf("vcs url scheme must be https")
}
mux := http.NewServeMux()
mux.Handle("/healthz", health())
mux.Handle("/", redirectPackage(vcs, u))
log.Printf("starting to listen on %s", addr)
if cert, key := os.Getenv("TLS_CERT"), os.Getenv("TLS_KEY"); cert != "" && key != "" {
err = http.ListenAndServeTLS(addr, cert, key, mux)
} else {
err = http.ListenAndServe(addr, mux)
}
if err != http.ErrServerClosed {
log.Fatalf("listen error: %+v", err)
}
log.Printf("server shutdown successfully")
}
func health() http.HandlerFunc {
return func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(200)
_, _ = w.Write([]byte("ok"))
}
}
func redirectPackage(vcs string, vcsURL *url.URL) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
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
URL string
}{
path.Join(r.Host, r.URL.Path),
vcs,
u.String(),
}
var buf bytes.Buffer
if err := tpl.Execute(&buf, &data); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("cache-Control", "no-store")
_, _ = w.Write(buf.Bytes())
}
}