Search code examples
webgorelative-pathstatic-files

How does the root of a Go web application get resolved?


Im using go's net/http library to serve up a web app. When users come to the site, they can simply go to /, and it serves index.html (like any site).

This is implemented using:

r.PathPrefix("/").Handler(http.FileServer(http.Dir("./")))

However, there are two ways to structure such an app. First you could pack all the files in the same directory. This seems to me to be a unstable solution (if I run the go file directly it fails).

src/bin/app.go
src/bin/index.html

Or, the more "traditional" style, where index.html is top level.

src/bin/app.go
index.html
  • Where is the right place for index.html, or other static resources in a go web app ?
  • How is the location of ./ determined once we pack a go file into a binary ?
  • Can a go binary file preserve a directory structure of non go resources so that this is consistent between dev and production environments?

UPDATE (The answer below is correct, and I implemented the suggestion by Not_a_golfer below and my dir tree looks like this, which is easy to maintain in any environment via conf or dynamic logic in the server).

├── src
│   └── main
│       └── app.go
└── static
    ├── index.html
    ├── script.js
    └── style.css

Solution

  • Since Go doesn't bundle assets into binaries, it's certainly not a good idea to keep your code and your assets bundled together.

    I recommend one of the following:

    First of all, in both cases - make your app configurable, so that it accepts where the static assets are saved, either via a command line flag or a config file. It should be an absolute path, as it is irrelevant to where the executable is stored.

    And either:

    1. Keep a completely separate project for the static assets, and as a build step make sure they are packed together. In fact, you can deploy them separately to your server, thus not having to restart the Go app if you're only deploying HTML/JS/image changes.

    2. Keep their sources together in the same project, but make a top level directory named "html" or "static" or whatever. No Go files are allowed under this directory. The deployment process should be the same as in #1.