embed package released on Golang v1.16, now you can include any of your files into your golang binary. You can also serve the embedded file as a static site. But when it comes to subdirectory, you need to handle it a bit different.
In this article, you will learn how to serve embedded files as a static site that stored inside a subdirectory.
To test if the
assets can be imported using
relative URL, you can write the
link rel and
script src like the snippet above. You can put anything inside your
index.js just to make sure it is loaded.
embed package is released, you used to use
http.Dir to serve a static site using Go like below:
And yes, it works like a charm. But, when it comes to
It doesn’t work because you didn’t specified which subdirectory will be served.
http.FS will serve the embedded files from
root, that’s why instead of
http://localhost:8000/, you need to access it using
But the other problem is, it makes your
absolute import not working.
/assets/js/index.js will not work because it accesses the file from the
To solve those problems, you can use
fs.Sub to get the subtree of the
embedded files. So you can start get the
frontend/public directory as a root.
Now, you can access the site using
http://localhost:8000/ and both your
absolute import works again!
Thank you for reading!