diff options
| author | Shulhan <ms@kilabit.info> | 2025-01-06 02:54:52 +0700 |
|---|---|---|
| committer | Shulhan <ms@kilabit.info> | 2025-01-07 00:13:55 +0700 |
| commit | 85ae94f62b75372943a8ffdd705ce932a7849a8d (patch) | |
| tree | ff55363d9e47729ce5d3c0be9fafa54d2cbd2e30 /server.go | |
| parent | 6593f4d2069790c73595f14b3312a8d83e61760e (diff) | |
| download | ciigo-85ae94f62b75372943a8ffdd705ce932a7849a8d.tar.xz | |
all: auto convert markup when HTTP client request GET to HTML file
In development mode, where [ServeOptions.IsDevelopment] is set to true
or when running "ciigo serve", the ciigo HTTP server will check if the
new markup file is newer than HTML file when user press refresh or
reload on the browser.
If its newer, it will convert the markup file and return the new content
of HTML file.
Diffstat (limited to 'server.go')
| -rw-r--r-- | server.go | 60 |
1 files changed, 60 insertions, 0 deletions
@@ -8,6 +8,8 @@ import ( "fmt" "html/template" "log" + "net/http" + "path" "strings" libhttp "git.sr.ht/~shulhan/pakakeh.go/lib/http" @@ -50,6 +52,9 @@ func (ciigo *Ciigo) InitHTTPServer(opts ServeOptions) (err error) { Address: opts.Address, EnableIndexHTML: opts.EnableIndexHTML, } + if opts.IsDevelopment { + httpdOpts.HandleFS = ciigo.onGet + } ciigo.HTTPServer, err = libhttp.NewServer(httpdOpts) if err != nil { @@ -164,3 +169,58 @@ func (ciigo *Ciigo) onSearch(epr *libhttp.EndpointRequest) (resBody []byte, err return resBody, nil } + +// onGet when user reload the page from browser, inspect the HTML file by +// checking if its older that the adoc. +// If yes, it will auto convert the adoc and return the new content of HTML +// files. +func (ciigo *Ciigo) onGet( + node *memfs.Node, _ http.ResponseWriter, req *http.Request, +) (out *memfs.Node) { + var ( + logp = `onGet` + file string + ) + + if node == nil { + file = req.URL.Path + } else { + if node.IsDir() { + file = path.Join(node.Path, `index.html`) + } else { + if len(req.URL.Path) > len(node.Path) { + file = req.URL.Path + } else { + file = node.Path + } + } + } + if file[len(file)-1] == '/' { + file = path.Join(file, `index.html`) + } + + var ( + fmarkup *FileMarkup + isNew bool + ) + fmarkup, isNew = ciigo.watcher.getFileMarkupByHTML(file) + if fmarkup == nil { + // File is not HTML or no markup files created from it. + return node + } + var err error + if isNew || ciigo.converter.shouldConvert(fmarkup) { + err = ciigo.converter.ToHTMLFile(fmarkup) + if err != nil { + log.Printf(`%s: failed to convert markup file %q: %s`, + logp, fmarkup.path, err) + return node + } + } + out, err = ciigo.serveOpts.Mfs.Get(file) + if err != nil { + log.Printf(`%s: failed to get %q: %s`, logp, file, err) + return node + } + return out +} |
