esc icon indicating copy to clipboard operation
esc copied to clipboard

Doc Suggestion: Add example of Handlers for serving individual files

Open Michael-F-Ellis opened this issue 6 years ago • 0 comments

First of all, thanks for creating this! It works well and the API is clean and simple.

I used it to bundle wasm and js into an example app so that a server and all content is bundled into the app. Some of my content is generated dynamically, so delegating everything to

http.FileServer(FS(false))

didn't seem workable. I ended up writing handler functions like the following to allow setting proper content headers. Seems to work very well, though I don't know if that's the cleanest possible way to code it.

// fsSendStatic serves the requested file from the ESC FS.
func fsSendStatic(w http.ResponseWriter, r *http.Request) {
	_, err := w.Write(FSMustByte(false, r.URL.Path))
	if err != nil {
		log.Fatalf("Writing file %s returned error: %v", r.URL.Path, err)
	}
}

// fsSendStaticJS serves the requested javascript file from the ESC FS.
func fsSendStaticJS(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/javascript")
	fsSendStatic(w, r)
}

// fsSendStaticWasm serves the requested WebAssembly file  from the ESC FS.
func fsSendStaticWasm(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/wasm")
	fsSendStatic(w, r)
}

It took a bit of trial and error to get it working. Just wondering if it might save others some time if the README included an example showing how to serve a mixture of static and dynamic content.

Michael-F-Ellis avatar Nov 24 '19 16:11 Michael-F-Ellis