Relative path in Go-ThrowExceptions

Exception or error:

I’m trying to understand a relative path building in Go. Here is my problem: I have a folders tree:


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?

How to solve:

Use the go/build package to find the absolute path of a package in a Go workspace:

importPath := "" // 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).

Leave a Reply

Your email address will not be published. Required fields are marked *