-1

I am getting nil for sampleFlags in my debugger when attempting to read my file test.json. I am not sure if it is a path issue or where the reader pointer is. How FetchFlags is triggered is by a handler in server.go that ultimately calls FetchFlags.

flags.go

package flags

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
)

type Flag struct {
    Name     string `json:"name"`
    Category string `json:"category"`
    Label    string `json:"label"`
}

func FetchFlags() []Flag {
    sampleFlags, _ := ioutil.ReadFile("test.json")
    fmt.Printf("File contents: %s", sampleFlags)
    var Flags []Flag
    _ = json.Unmarshal(sampleFlags, &Flags)
    return Flags
}

Structure:

/server
  server.go
/package
  /flags
    flags.go
    test.json
  /pack_a
  /pack_b
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Liondancer
  • 15,721
  • 51
  • 149
  • 255

2 Answers2

1

You are trying to open file relative to package path. This is a bad design approach. For example depending on compilation method Go may place binaries in $GOROOT/bin directory. And there will not be the test.json file.

Use absolute path for your file or use approaches from How can I open files relative to my GOPATH?.

Alexander Yancharuk
  • 13,817
  • 5
  • 55
  • 55
1

The path should be relatve to your main.go(or equivalent) file and not your package. (Absolute path should work as well but I am not 100% sure about that)

If you think about it then you will realize that package/flags is directly or indirectly imported into your main file. Your code compilation/execution isn't jumping to package/flags, instead that code is imported to your main file.

I would recommend you to use abosulte path or path relative to your main file.

Omkar Rokade
  • 120
  • 1
  • 9