19 "github.com/mjl-/mox/mlog"
20 "github.com/mjl-/mox/moxvar"
23// WebappFile serves a merged HTML and JS webapp as a single compressed, cacheable
24// file. It merges the JS into the HTML at first load, caches a gzipped version
25// that is generated on first need, and responds with a Last-Modified header.
26type WebappFile struct {
27 HTML, JS []byte // Embedded html/js data.
28 HTMLPath, JSPath string // Paths to load html/js from during development.
29 CustomStem string // For trying to read css/js customizations from $configdir/$stem.{css,js}.
34 mtime time.Time // For Last-Modified and conditional request.
37// FallbackMtime returns a time to use for the Last-Modified header in case we
38// cannot find a file, e.g. when used in production.
39func FallbackMtime(log mlog.Log) time.Time {
40 p, err := os.Executable()
41 log.Check(err, "finding executable for mtime")
44 log.Check(err, "stat on executable for mtime")
49 log.Info("cannot find executable for webappfile mtime, using current time")
53func (a *WebappFile) serverError(log mlog.Log, w http.ResponseWriter, err error, action string) {
54 log.Errorx("serve webappfile", err, slog.String("msg", action))
55 http.Error(w, "500 - internal server error", http.StatusInternalServerError)
58// Serve serves a combined file, with headers for caching and possibly gzipped.
59func (a *WebappFile) Serve(ctx context.Context, log mlog.Log, w http.ResponseWriter, r *http.Request) {
60 // We typically return the embedded file, but during development it's handy
62 fhtml, _ := os.Open(a.HTMLPath)
66 fjs, _ := os.Open(a.JSPath)
74 var diskmtime time.Time
76 if fhtml != nil && fjs != nil {
77 sth, err := fhtml.Stat()
79 a.serverError(log, w, err, "stat html")
82 stj, err := fjs.Stat()
84 a.serverError(log, w, err, "stat js")
88 maxmtime := sth.ModTime()
89 if stj.ModTime().After(maxmtime) {
90 maxmtime = stj.ModTime()
94 refreshdisk = maxmtime.After(a.mtime) || a.combined == nil
98 html, err = io.ReadAll(fhtml)
100 a.serverError(log, w, err, "reading html")
103 js, err = io.ReadAll(fjs)
105 a.serverError(log, w, err, "reading js")
112 // Check mtime of css/js files.
113 var haveCustomCSS, haveCustomJS bool
114 checkCustomMtime := func(ext string, have *bool) bool {
115 path := ConfigDirPath(a.CustomStem + "." + ext)
116 if fi, err := os.Stat(path); err != nil {
117 if !errors.Is(err, fs.ErrNotExist) {
118 a.serverError(log, w, err, "stat customization file")
121 } else if mtm := fi.ModTime(); mtm.After(diskmtime) {
127 if !checkCustomMtime("css", &haveCustomCSS) || !checkCustomMtime("js", &haveCustomJS) {
130 // Detect removal of custom files.
131 if fi, err := os.Stat(ConfigDirPath(".")); err == nil && fi.ModTime().After(diskmtime) {
132 diskmtime = fi.ModTime()
136 refreshdisk = refreshdisk || diskmtime.After(a.mtime)
148 if refreshdisk || a.combined == nil {
149 var customCSS, customJS []byte
152 customCSS, err = os.ReadFile(ConfigDirPath(a.CustomStem + ".css"))
154 a.serverError(log, w, err, "read custom css file")
159 customJS, err = os.ReadFile(ConfigDirPath(a.CustomStem + ".js"))
161 a.serverError(log, w, err, "read custom js file")
166 cssp := []byte(`/* css placeholder */`)
167 cssi := bytes.Index(html, cssp)
169 a.serverError(log, w, errors.New("css placeholder not found"), "generating combined html")
172 jsp := []byte(`/* js placeholder */`)
173 jsi := bytes.Index(html, jsp)
175 a.serverError(log, w, errors.New("js placeholder not found"), "generating combined html")
180 fmt.Fprintf(&b, "/* Custom CSS by admin from $configdir/%s.css: */\n", a.CustomStem)
182 b.Write(html[cssi+len(cssp) : jsi])
183 fmt.Fprintf(&b, "// Custom JS by admin from $configdir/%s.js:\n", a.CustomStem)
185 fmt.Fprintf(&b, "\n// Javascript is generated from typescript, don't modify the javascript because changes will be lost.\nconst moxversion = \"%s\";\nconst moxgoos = \"%s\";\nconst moxgoarch = \"%s\";\n", moxvar.Version, runtime.GOOS, runtime.GOARCH)
187 b.Write(html[jsi+len(jsp):])
193 a.mtime = FallbackMtime(log)
200 if a.combinedGzip == nil {
202 gzw, err := gzip.NewWriterLevel(&b, gzip.BestCompression)
204 _, err = gzw.Write(out)
210 a.serverError(log, w, err, "gzipping combined html")
213 a.combinedGzip = b.Bytes()
215 origSize = int64(len(out))
225 w.Header().Set("Content-Type", "text/html; charset=utf-8")
226 http.ServeContent(gzipInjector{w, gz, origSize}, r, "", mtime, bytes.NewReader(out))
229// gzipInjector is a http.ResponseWriter that optionally injects a
230// Content-Encoding: gzip header, only in case of status 200 OK. Used with
231// http.ServeContent to serve gzipped content if the client supports it. We cannot
232// just unconditionally add the content-encoding header, because we don't know
233// enough if we will be sending data: http.ServeContent may be sending a "not
234// modified" response, and possibly others.
235type gzipInjector struct {
236 http.ResponseWriter // Keep most methods.
241// WriteHeader adds a Content-Encoding: gzip header before actually writing the
242// headers and status.
243func (w gzipInjector) WriteHeader(statusCode int) {
244 if w.gz && statusCode == http.StatusOK {
245 w.ResponseWriter.Header().Set("Content-Encoding", "gzip")
246 if lw, ok := w.ResponseWriter.(interface{ SetUncompressedSize(int64) }); ok {
247 lw.SetUncompressedSize(w.origSize)
250 w.ResponseWriter.WriteHeader(statusCode)
253// AcceptsGzip returns whether the client accepts gzipped responses.
254func AcceptsGzip(r *http.Request) bool {
255 s := r.Header.Get("Accept-Encoding")
256 t := strings.Split(s, ",")
257 for _, e := range t {
258 e = strings.TrimSpace(e)
259 tt := strings.Split(e, ";")
260 if len(tt) > 1 && t[1] == "q=0" {