-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
167 lines (152 loc) · 3.67 KB
/
server.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
package main
import (
"encoding/base64"
"fmt"
"gconf/github"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/julienschmidt/httprouter"
)
type Server struct {
loader *loader
snapshot *configSnapshot
updateDuration time.Duration
}
func NewServer(repoOwner, repoName string, updateDuration time.Duration) *Server {
token := os.Getenv("TOKEN")
client := &http.Client{
Transport: newModifyingTransport(http.DefaultTransport, func(r *http.Request) {
log.Printf("%s %s", r.Method, r.URL.String())
if token != "" {
r.Header.Add("Authorization", fmt.Sprintf("token %s", token))
}
}),
}
return &Server{
updateDuration: updateDuration,
loader: &loader{
client: client,
githubAPIHost: github.DefaultHost,
repoOwner: repoOwner,
repoName: repoName,
repoSHA: "master",
},
}
}
func (s *Server) ListenAndServe(address string) error {
// Attempt initial load.
if err := s.update(); err != nil {
return err
}
// Spawn worker to refresh periodically.
ticker := time.NewTicker(s.updateDuration)
quit := make(chan struct{})
defer close(quit)
go func() {
for {
select {
case <-ticker.C:
if err := s.update(); err != nil {
log.Printf("failed to update: %v", err)
}
case <-quit:
ticker.Stop()
return
}
}
}()
r := httprouter.New()
r.GET("/", s.HandleIndex)
r.GET("/file/*filename", s.HandleFile)
return http.ListenAndServe(address, r)
}
func (s *Server) HandleIndex(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fmt.Fprintf(w, "<!DOCTYPE html><html><body>")
for _, config := range s.snapshot.configs {
fmt.Fprintf(w, "<a href='/file/%s'/>%s</a>", config.path, config.path)
fmt.Fprintf(w, "<br/>")
}
fmt.Fprintf(w, "</body></html>")
}
func (s *Server) HandleFile(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
filename := ps.ByName("filename")
filename = strings.TrimSpace(filename)
filename = strings.TrimLeft(filename, "/")
if filename == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
for _, config := range s.snapshot.configs {
if config.path == filename {
eTag := config.blob.SHA
if r.Header.Get("If-None-Match") == eTag {
w.WriteHeader(http.StatusNotModified)
return
}
content, err := base64.StdEncoding.DecodeString(config.blob.Content)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Println(err)
return
}
maxAge := fmt.Sprintf("max-age=%s", s.updateDuration)
w.Header().Add("Cache-Control", maxAge)
w.Header().Add("ETag", eTag)
if _, err := fmt.Fprintf(w, string(content)); err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Println(err)
}
return
}
}
w.WriteHeader(http.StatusNotFound)
}
func (s *Server) update() error {
snapshot, err := s.loader.Load()
if err != nil {
return err
}
s.snapshot = snapshot
return nil
}
type loader struct {
client *http.Client
githubAPIHost string
repoOwner string
repoName string
repoSHA string
}
func (l *loader) Load() (*configSnapshot, error) {
res, err := github.GetTree(l.client, l.githubAPIHost, l.repoOwner, l.repoName, l.repoSHA, true)
if err != nil {
return nil, err
}
cs := &configSnapshot{}
for _, node := range res.Tree {
switch node.Type {
case "tree":
continue
case "blob":
// Node is a file.
blob, err := github.GetBlob(l.client, l.githubAPIHost, l.repoOwner, l.repoName, node.SHA)
if err != nil {
return nil, err
}
cs.configs = append(cs.configs, config{
path: node.Path,
blob: blob,
})
}
}
return cs, nil
}
type configSnapshot struct {
configs []config
}
type config struct {
path string
blob *github.GetBlobResponse
}