I have a quick question about serving files in Go. There is the great timesaving FileServer handler, but for my use case, I only have 2 or 3 files (js and css) that go with my app and I dont want to complicate the deployment to have to think about those.
Do you think there is an easy way to build those couple of files into the binary and serve them from there. For example base64 encode the data of the files as constants and server the files from the constants. This would work in its most simple form, but I dont want to go through the pain of doing everything that a file server does (headers, expiries, mime-types, etc) on my own. So would there be an easy way to bake those static files into the binary in some form and serve them that way?
The "go.rice" package takes care of this for you - embedding resources in your binaries, and providing an http.FileSystem implementation.
I would store the files in variable as plain text. Something like this:
That way, it is pretty easy to have your makefile or build script so something like:
for file in index.html style.css; do echo "package main\nfunc init() { files[\"$file\"] = \`$(cat $file)\` }" | gofmt -s > $file.go; done; go build && ./httptest
The
FileServer
requires aFileSystem
object in its constructor. Usually, you would provide something based onhttp.Dir
to make thatFileSystem
for you from the actual file system, but nothing prevents you from implementing your own:This implementation is very buggy at best, and you should probably never ever use it, but it should show you how the
FileSystem
interface can be implemented for arbitrary 'files'.A more credible (and certainly less dangerous) implementation of something similar is available here. This is the one used to fake the filesystem on Go playground, so it should be a good reference (much better than mine anyway).
Whether it is simpler to reimplement this
FileSystem
interface or a customFileServer
as other suggested, is entirely up to you and your project ! I suspect however that for serving a couple of predefined files, rewriting the serving part might be easier than emulating a full file-system.It is not very difficult to do what you request. You don't have to base64 encode it or anything (it will just make it harder for you to edit.).
Below is an example of how to output a javascript file with correct mime type: