Reputation: 1275
I'm trying to understand a relative path building in Go. Here is my problem: I have a folders tree:
-root
--main
---utils
---certs
--tests
Having my certificates uploaded into certs folder and connectivity util.go
file uploaded into utils
, I have relative paths hard coded in the file.
Problem: Having paths specified in utils/util.go
, they work fine once called from main/main.go
and throw exception (file not found) when called from tests/test.go
.
What's the way out?
Upvotes: 4
Views: 6551
Reputation: 120951
Use the go/build package to find the absolute path of a package in a Go workspace:
importPath := "github.com/user/root/main" // modify to match import path of main
p, err := build.Default.Import(importPath, "", build.FindOnly)
if err != nil {
// handle error
}
certsDir := filepath.Join(p.Dir, "certs")
This only works when run in the context of a Go workspace (the source code is available and GOPATH is set).
Upvotes: 3