-
-
Notifications
You must be signed in to change notification settings - Fork 366
/
static.go
89 lines (77 loc) · 1.79 KB
/
static.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
// +build !wasm
package app
import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"github.com/maxence-charriere/go-app/v7/pkg/errors"
)
// GenerateStaticWebsite generates the files to run a PWA built with go-app as a
// static website in the specified directory. Static websites can be used with
// hosts such as Github Pages.
//
// Note that app.wasm must still be built separately and put into the web
// directory.
func GenerateStaticWebsite(dir string, h *Handler) error {
if err := os.MkdirAll(filepath.Join(dir, "web"), 0755); err != nil {
return errors.New("creating directory for static website failed").
Tag("directory", dir).
Wrap(err)
}
resources := []struct {
filename string
path string
}{
{
filename: "index.html",
path: "/",
},
{
filename: "wasm_exec.js",
path: "/wasm_exec.js",
},
{
filename: "app.js",
path: "/app.js",
},
{
filename: "app-worker.js",
path: "/app-worker.js",
},
{
filename: "manifest.json",
path: "/manifest.json",
},
{
filename: "app.css",
path: "/app.css",
},
}
for _, r := range resources {
filename := filepath.Join(dir, r.filename)
f, err := os.Create(filename)
if err != nil {
return errors.New("create file failed").
Tag("filename", filename).
Wrap(err)
}
defer f.Close()
req, err := http.NewRequest(http.MethodGet, "http://go-app.io"+r.path, nil)
if err != nil {
return errors.New("creating file request failed").
Tag("filename", filename).
Tag("path", r.path).
Wrap(err)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if n, err := f.Write(rec.Body.Bytes()); err != nil {
return errors.New("writing file failed").
Tag("filename", filename).
Tag("bytes-written", n).
Wrap(err)
}
}
return nil
}