Spearfisher
Spearfisher

Reputation: 8763

Setting up absolute file path in Golang

I am a package whose only role is to provide a collection of dummy data read from files.

It looks like this:

func GetArrayOfSize(n int) []int {
f, _ := os.Open("./arrays.txt")
defer f.Close()

numbers := make([]int, 0)
scanner := bufio.NewScanner(f)

for scanner.Scan() {
    s, _ := strconv.Atoi(scanner.Text())
    numbers = append(numbers, s)
}

    return numbers[0:n]
}

It works fine when I test it inside this package however whenever I call GetArrayOfSize from another package I get a runtime error:

panic: runtime error: slice bounds out of range [recovered]
    panic: runtime error: slice bounds out of range

I am guessing this error is due to the relative path: './arrays.txt. How can I fetch the absolute path of my dummy package to fix this?

Many thanks

Upvotes: 1

Views: 1809

Answers (2)

Thundercat
Thundercat

Reputation: 120931

You should check the error return from os.Open and handle it.

You can get the absolute path to the source code directory using the go/build package:

p, err := build.Default.Import("github.com/user/repo/dummy", "", build.FindOnly)
if err != nil {
    // handle error
}
fname := filepath.Join(p.Dir, "arrays.txt")

This code assumes that the GOPATH environment variable is set.

Upvotes: 1

Quinn Carver
Quinn Carver

Reputation: 605

Run the install command with the go tool and you should be able to run your command from anywhere on your system. Here's a good link that gives an example of the install command: How To Write Go Code

Upvotes: 0

Related Questions