how to reference a relative file from code and tests

Relative paths are always interpreted / resolved to a base path: the current or working directory - therefore it will always have its limitations.

If you can live with always taking care of the proper working directory, you may keep using relative paths.

What I would suggest is to not rely on the working directory, but an explicitly specified base path. This may have a default value hard-coded in your application (which may be the working directory as well), and you should provide several ways to override its value.

Recommended ways to override the base path to which your "relative" paths are resolved against:

  1. Command line flag (see flag package)
  2. Environment variable (see os.Getenv())
  3. (Fix named) Config file in user's home directory (see os/user/User and os/user/Current())

Once you have the base path, you can get the full path by joining the base path and the relative path. You may use path.Join() or filepath.Join(), e.g.:

// Get base path, from any or from the combination of the above mentioned solutions
base := "/var/myapp"

// Relative path, resource to read/write from:
relf := "conf/patients.json"

// Full path that identifies the resource:
full := filepath.Join(base, relf) // full will be "/var/myapp/conf/patients.json"

I've never used Revel myself but the following looks helpful to me:

http://revel.github.io/docs/godoc/revel.html

  • revel.BasePath
  • revel.AppPath