-
Notifications
You must be signed in to change notification settings - Fork 3
/
patchbay.go
127 lines (101 loc) · 3.69 KB
/
patchbay.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
package patchbay
import (
"fmt"
"log"
"io/ioutil"
"strings"
"net/http"
"os"
"path"
)
var ValidExt = [...]string{".html", ".js", ".ico", ".css", ".jpg", ".svg"}
type Hoster struct {
rootChannel string
dir string
client *http.Client
authToken string
numWorkers int
}
func (h *Hoster) Start() {
h.HostDir(h.rootChannel, h.dir, h.numWorkers)
}
func (h *Hoster) HostDir(channel string, dirPath string, numWorkers int) {
entries, err := ioutil.ReadDir(dirPath)
if err != nil {
log.Fatal(err)
}
for _, entry := range entries {
if entry.IsDir() && !strings.HasPrefix(entry.Name(), ".") {
h.HostDir(channel + "/" + entry.Name(), path.Join(dirPath, entry.Name()), h.numWorkers)
} else {
if validExt(entry.Name()) {
h.HostFile(channel + "/" + entry.Name(), path.Join(dirPath, entry.Name()), h.numWorkers)
}
// also host index files directly on the path
if entry.Name() == "index.html" {
//h.HostFile(channel, path.Join(dirPath, entry.Name()), h.numWorkers)
h.HostFile(channel + "/", path.Join(dirPath, entry.Name()), h.numWorkers)
}
}
}
}
func (h *Hoster) HostFile(channel string, path string, numWorkers int) {
for i := 0; i < numWorkers; i++ {
go func(index int) {
for {
file, err := os.Open(path)
if err != nil {
log.Fatal(err)
}
req, err := http.NewRequest("POST", channel + "?responder=true", file)
if err != nil {
log.Fatal(err)
}
if h.authToken != "" {
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", h.authToken))
}
res, err := h.client.Do(req)
if err != nil {
log.Fatal(err)
}
log.Println(fmt.Sprintf("Served %s on channel %s from worker %d", path, channel, index))
if res.StatusCode > 299 {
log.Println("Something went wrong")
}
}
}(i)
}
}
func validExt(path string) bool {
for _, ext := range ValidExt {
if strings.HasSuffix(path, ext) {
return true
}
}
return false
}
type HosterBuilder struct {
hoster Hoster
}
func (h *HosterBuilder) Dir(dir string) *HosterBuilder {
h.hoster.dir = dir
return h
}
func (h *HosterBuilder) RootChannel(channel string) *HosterBuilder {
h.hoster.rootChannel = channel
return h
}
func (h *HosterBuilder) AuthToken(token string) *HosterBuilder {
h.hoster.authToken = token
return h
}
func (h *HosterBuilder) NumWorkers(n int) *HosterBuilder {
h.hoster.numWorkers = n
return h
}
func (h *HosterBuilder) Build() *Hoster {
return &h.hoster
}
func NewHosterBuilder() *HosterBuilder {
return &HosterBuilder{hoster: Hoster{dir:".", client: &http.Client{}}}
}