-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
87 lines (77 loc) · 1.64 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
package main
import (
"html/template"
"log"
"net/http"
"os"
"github.com/abennett/vangen/repos"
"github.com/go-chi/chi"
)
const (
repoNameParam = "repo_name"
vanityDomainEnv = "VANITY_DOMAIN"
portEnv = "PORT"
)
type VanityService struct {
url string
template *template.Template
repos map[string]string
}
type repo struct {
Name string
GithubURL string
VanityDomain string
}
func NewVanityService(url string) *VanityService {
tmpl, err := template.New("goPage").Parse(pageTemplate)
if err != nil {
panic(err)
}
return &VanityService{
url: url,
template: tmpl,
repos: repos.Repos,
}
}
func (vs *VanityService) GetRepo(name string) (*repo, bool) {
githubURL, ok := vs.repos[name]
if !ok {
return nil, false
}
return &repo{
Name: name,
GithubURL: githubURL,
VanityDomain: vs.url,
}, true
}
func (vs *VanityService) mux() *chi.Mux {
r := chi.NewMux()
r.Get("/{repo_name}", vs.repoHandlerFunc)
return r
}
func (vs *VanityService) repoHandlerFunc(w http.ResponseWriter, r *http.Request) {
repoName := chi.URLParam(r, repoNameParam)
repo, ok := vs.GetRepo(repoName)
if !ok {
http.Error(w, repoName+" not found", http.StatusNotFound)
return
}
if err := vs.template.Execute(w, repo); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
return
}
func main() {
port, ok := os.LookupEnv(portEnv)
if !ok {
port = ":8080"
}
domain, ok := os.LookupEnv(vanityDomainEnv)
if !ok {
log.Fatal("must specify VANITY_DOMAIN")
}
vs := NewVanityService(domain)
log.Printf("Listening on %s", port)
log.Fatal(http.ListenAndServe(port, vs.mux()))
}