17 "github.com/mjl-/mox/mlog"
18 "github.com/mjl-/mox/moxvar"
21// WebappFile serves a merged HTML and JS webapp as a single compressed, cacheable
22// file. It merges the JS into the HTML at first load, caches a gzipped version
23// that is generated on first need, and responds with a Last-Modified header.
24type WebappFile struct {
25 HTML, JS []byte // Embedded html/js data.
26 HTMLPath, JSPath string // Paths to load html/js from during development.
31 mtime time.Time // For Last-Modified and conditional request.
34// FallbackMtime returns a time to use for the Last-Modified header in case we
35// cannot find a file, e.g. when used in production.
36func FallbackMtime(log mlog.Log) time.Time {
37 p, err := os.Executable()
38 log.Check(err, "finding executable for mtime")
41 log.Check(err, "stat on executable for mtime")
46 log.Info("cannot find executable for webappfile mtime, using current time")
50func (a *WebappFile) serverError(log mlog.Log, w http.ResponseWriter, err error, action string) {
51 log.Errorx("serve webappfile", err, slog.String("msg", action))
52 http.Error(w, "500 - internal server error", http.StatusInternalServerError)
55// Serve serves a combined file, with headers for caching and possibly gzipped.
56func (a *WebappFile) Serve(ctx context.Context, log mlog.Log, w http.ResponseWriter, r *http.Request) {
57 // We typically return the embedded file, but during development it's handy
59 fhtml, _ := os.Open(a.HTMLPath)
63 fjs, _ := os.Open(a.JSPath)
71 var diskmtime time.Time
73 if fhtml != nil && fjs != nil {
74 sth, err := fhtml.Stat()
76 a.serverError(log, w, err, "stat html")
79 stj, err := fjs.Stat()
81 a.serverError(log, w, err, "stat js")
85 maxmtime := sth.ModTime()
86 if stj.ModTime().After(maxmtime) {
87 maxmtime = stj.ModTime()
91 refreshdisk = maxmtime.After(a.mtime) || a.combined == nil
95 html, err = io.ReadAll(fhtml)
97 a.serverError(log, w, err, "reading html")
100 js, err = io.ReadAll(fjs)
102 a.serverError(log, w, err, "reading js")
118 if refreshdisk || a.combined == nil {
119 script := []byte(`<script>/* placeholder */</script>`)
120 index := bytes.Index(html, script)
122 a.serverError(log, w, errors.New("script not found"), "generating combined html")
126 b.Write(html[:index])
127 fmt.Fprintf(&b, "<script>\n// Javascript is generated from typescript, don't modify the javascript because changes will be lost.\nconst moxversion = \"%s\";\n", moxvar.Version)
129 b.WriteString("\t\t</script>")
130 b.Write(html[index+len(script):])
136 a.mtime = FallbackMtime(log)
143 if a.combinedGzip == nil {
145 gzw, err := gzip.NewWriterLevel(&b, gzip.BestCompression)
147 _, err = gzw.Write(out)
153 a.serverError(log, w, err, "gzipping combined html")
156 a.combinedGzip = b.Bytes()
158 origSize = int64(len(out))
164 w.Header().Set("Content-Type", "text/html; charset=utf-8")
165 http.ServeContent(gzipInjector{w, gz, origSize}, r, "", mtime, bytes.NewReader(out))
168// gzipInjector is a http.ResponseWriter that optionally injects a
169// Content-Encoding: gzip header, only in case of status 200 OK. Used with
170// http.ServeContent to serve gzipped content if the client supports it. We cannot
171// just unconditionally add the content-encoding header, because we don't know
172// enough if we will be sending data: http.ServeContent may be sending a "not
173// modified" response, and possibly others.
174type gzipInjector struct {
175 http.ResponseWriter // Keep most methods.
180// WriteHeader adds a Content-Encoding: gzip header before actually writing the
181// headers and status.
182func (w gzipInjector) WriteHeader(statusCode int) {
183 if w.gz && statusCode == http.StatusOK {
184 w.ResponseWriter.Header().Set("Content-Encoding", "gzip")
185 if lw, ok := w.ResponseWriter.(interface{ SetUncompressedSize(int64) }); ok {
186 lw.SetUncompressedSize(w.origSize)
189 w.ResponseWriter.WriteHeader(statusCode)
192// AcceptsGzip returns whether the client accepts gzipped responses.
193func AcceptsGzip(r *http.Request) bool {
194 s := r.Header.Get("Accept-Encoding")
195 t := strings.Split(s, ",")
196 for _, e := range t {
197 e = strings.TrimSpace(e)
198 tt := strings.Split(e, ";")
199 if len(tt) > 1 && t[1] == "q=0" {