How to handle paths for supporting files in a package in Go?

Go program with the following structure:-

├── app.go
├── bin
│   └── run.go
├── config
│   └── Config.go
└── package1
    ├── package1_file.go
    └── tmpl
        └── template.tmpl

Now, in package1_file.go, I’ve accessed template.tmpl via relative path like:

t, err := template.ParseFiles("./tmpl/template.tmpl")

When I run tests, tests are able to run successfully because my guess is, Go changes the current working directory when running tests for packages. go tests -v ./...

However, when I run (go build -o app && ./app) the program from the root folder, I get error complaining that file doesn’t exist.

Error compiling template: open ./tmpl/template.tmpl: no such file or directory

It starts working when I change the path to package2/tmpl/template.tmpl.

The code outside package2 has nothing to do with this template file so I don’t want to expose it as a parameter to a function while exposing package2. What are my options?

What is the right way to target support files like these?

1 Like

A good practice that I recommend you for managing the paths inside your programs is defining an absolute path to your application.

folder, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		log.Fatalln(err)
	}

Now you can use your tmpl folder no matter where you’re running the program, eg:

if _, err := templ.ParseGlob(filepath.Join(folder, "tmpl", "*.html")); err != nil {
		log.Fatalln(err)
	}
2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.