在同一包中的两个源文件之间共享变量

I am working on a project in Go. For organization, I have the code split up into files:

  • server related functions go in server.go
  • database handling goes in db.go
  • global variables are in types.go
  • etc.

I declared a variable document_root in types.go, and defined it in main.go with:

document_root,error := config.GetString("server","document_root")

In server.go, I have a function to generate an HTTP status code for the requested file, and it does:

_, err := os.Stat(document_root+"/"+filename);

Upon compiling, I'm getting this error:

"document_root declared and not used"

What am I doing wrong?

I'm assuming in types.go, you're declaring document_root at the package scope. If so, the problem is this line:

document_root, error := config.GetString("server", "document_root")

Here, you're unintentionally creating another document_root variable local to the main function. You need to write something like this:

var err error
document_root, err = config.GetString("server", "document_root")