-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.go
More file actions
66 lines (53 loc) · 1.38 KB
/
server.go
File metadata and controls
66 lines (53 loc) · 1.38 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
package toolshed
import (
"fmt"
"log"
"net/http"
"path/filepath"
"strings"
)
const errorScript = `echo "failed to fetch upstream script" && exit 1`
type server struct {
logger *log.Logger
listen string
fetcher fetcher
}
func (s *server) handleIndex() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
version := parseVersion(r.URL.Path)
script, err := s.fetcher.Fetch(version)
if err != nil {
s.logger.Printf("request failed for %s: %s", version, err)
http.Error(w, errorScript, http.StatusInternalServerError)
return
}
if version != "master" {
val := fmt.Sprintf(`BELT_VERSION="%s"`, version)
script = strings.Replace(script, `BELT_VERSION="master"`, val, 1)
}
s.logger.Printf("request succeeded for %s", version)
w.Write([]byte(script))
}
}
func (s *server) handleInvalidate() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
s.fetcher.Invalidate()
s.logger.Println("cache invalidated")
w.WriteHeader(http.StatusNoContent)
}
}
func (s *server) Routes() {
http.HandleFunc("/", s.handleIndex())
http.HandleFunc("/invalidate", s.handleInvalidate())
}
func (s *server) Run() error {
s.logger.Printf("server running at %s", s.listen)
return http.ListenAndServe(s.listen, nil)
}
func parseVersion(path string) string {
base := filepath.Base(path)
if base == "/" {
return "master"
}
return base
}