4

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?

11
  • 3
    Possible duplicate of how to reference a relative file from code and tests Commented Apr 25, 2016 at 14:29
  • No it does not look to be duplicate. There topicstarter uses some revel framework, when for me it fails for base golang functionality... Commented Apr 25, 2016 at 14:36
  • Please read the answer I gave there and don't get blocked by the word "revel". Commented Apr 25, 2016 at 14:37
  • Hmm im not sure what exactly do u suggest.. A base path for the cert files is exactly same. The difference in the caller path. Having known my basepath how would i use it in golang to restore fullpath? Commented Apr 25, 2016 at 14:40
  • You may use path.Join() or filepath.Join() to get the full path. I edited my answer to show an example of it. Commented Apr 25, 2016 at 14:47

1 Answer 1

3

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.