software development, devops, and other drivel
Tree lined path

Go embed example of serving static files at the root URL path

Go 1.16 introduced the embed package which allows serving static files from directly within the binary without the need for any external package.

Screenshot of the example web page
Screenshot of the example web page

Here are two example’s showing how to serve from the root URL path.

example.go shows an example of how to use the new io/fs package and the Sub func. The comments offer a word of caution however that it may not prevent access outside of the subdirectory.

Word of caution

main.go This was my original attempt at serving a subdirectory at the root of the URL before I realized what the new io/fs package provided. This method does however allow the addition of headers and other possible modifications.

How to

  • View the complete gist.
  • Download example.go or main.go or…both
  • Create the directories mkdir -p public/css
  • Download index.html within the public directory.
  • Download style.css within the public/css directory.
  • Build and run example.go or main.go.