-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfetcher.go
More file actions
76 lines (59 loc) · 1.32 KB
/
fetcher.go
File metadata and controls
76 lines (59 loc) · 1.32 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
package toolshed
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"sync"
)
type fetcher interface {
Fetch(string) (string, error)
Invalidate()
}
type githubFetcher struct {
logger *log.Logger
repo string
mu sync.Mutex
cache map[string]string
}
func (g *githubFetcher) Fetch(version string) (string, error) {
script := g.cacheGet(version)
if script != "" {
return script, nil
}
g.logger.Printf("not cached, fetching script from github...")
url := g.generateURL(version)
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("fetcher request failed for: %s", url)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
script = string(body)
g.cachePut(version, script)
return script, err
}
func (g *githubFetcher) Invalidate() {
g.mu.Lock()
defer g.mu.Unlock()
g.cache = make(map[string]string)
}
func (g *githubFetcher) cacheGet(version string) string {
g.mu.Lock()
defer g.mu.Unlock()
return g.cache[version]
}
func (g *githubFetcher) cachePut(version, script string) {
g.mu.Lock()
defer g.mu.Unlock()
g.cache[version] = script
}
func (g *githubFetcher) generateURL(version string) string {
return fmt.Sprintf("https://raw.githubusercontent.com/%s/%s/setup.sh", g.repo, version)
}