/
main.go
152 lines (122 loc) · 2.46 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
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
package main
import (
"bytes"
"crypto/md5"
"encoding/hex"
"flag"
"fmt"
"go/format"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path"
"path/filepath"
"sort"
"strings"
"text/template"
)
var (
staticDir string
benchDir string
)
func init() {
flag.StringVar(&benchDir, "benchdir", "bench", "path to bench/src/bench directory")
flag.StringVar(&staticDir, "staticdir", "webapp/public", "path to webapp/public directory")
}
func must(err error) {
if err != nil {
panic(err)
}
}
type hasherTransport struct {
targetHost string
t http.RoundTripper
}
func (ct *hasherTransport) RoundTrip(req *http.Request) (*http.Response, error) {
host := req.URL.Host
defer func() {
req.URL.Host = host
}()
req.URL.Host = ct.targetHost
res, err := ct.t.RoundTrip(req)
return res, err
}
type TemplateArg struct {
StaticFiles []*StaticFile
}
type StaticFile struct {
Path string
Size int64
Hash string
}
const staticFileTemplate = `
package bench
type StaticFile struct {
Path string
Size int64
Hash string
}
var StaticFiles = []*StaticFile {
{{ range .StaticFiles }} &StaticFile { "{{ .Path }}", {{ .Size }}, "{{ .Hash }}" },
{{ end }}
}
`
func prepareStaticFiles() []*StaticFile {
var ret []*StaticFile
err := filepath.Walk(staticDir, func(path string, info os.FileInfo, err error) error {
must(err)
if info.IsDir() {
return nil
}
if strings.HasSuffix(path, ".map") {
return nil
}
subPath := path[len(staticDir):]
subPath = strings.TrimSuffix(subPath, "index.html")
f, err := os.Open(path)
must(err)
defer f.Close()
h := md5.New()
_, err = io.Copy(h, f)
must(err)
hash := hex.EncodeToString(h.Sum(nil))
ret = append(ret, &StaticFile{
Path: subPath,
Size: info.Size(),
Hash: hash,
})
return nil
})
must(err)
// canonicalize
sort.Slice(ret, func(i, j int) bool {
return ret[i].Path < ret[j].Path
})
return ret
}
func writeStaticFileGo() {
const saveName = "staticfile.go"
files := prepareStaticFiles()
t := template.Must(template.New(saveName).Parse(staticFileTemplate))
var buf bytes.Buffer
t.Execute(&buf, TemplateArg{
StaticFiles: files,
})
fmt.Print(buf.String())
data, err := format.Source(buf.Bytes())
must(err)
err = ioutil.WriteFile(path.Join(benchDir, saveName), data, 0644)
must(err)
log.Println("save", saveName)
}
func main() {
flag.Parse()
var err error
staticDir, err = filepath.Abs(staticDir)
must(err)
benchDir, err = filepath.Abs(benchDir)
must(err)
writeStaticFileGo()
}