GoLang和带有相对路径的软件包布局

I'm learning Go language and I've made this example: http://thenewstack.io/make-a-restful-json-api-go/ to build a simple REST API.

I've compiled it and all works fine but all sources are in the main package.

Now I want to organize my .go files in packages, so I move them into some folders this way:

GOPATH\bin
GOPATH\pkg
GOPATH\src\pack1\Handlers.go
GOPATH\src\pack1\Logger.go
GOPATH\src\pack1epo.go
GOPATH\src\pack1\Todo.go
GOPATH\srcouter\Router.go
GOPATH\srcouter\Routes.go
GOPATH\src\Main.go

Main.go uses all the router package so I've put in the import section: "./router". Router.go uses the pack1 package, so in Router.go I've imported "../pack1". Now if I try to "go build Main.go" I get:

router\Router.go:6: imported and not used: "_/D_/GOPATH/src/pack1"
router\Router.go:14: undefined: Logger

and similar errors, so seems that the import of pack1 package that I've made, it's wrong. Of course in all files belonging to pack1, in the header I've put the "package pack1" definition.

I've also read that the relative imports are not suggested in Go and it could be useful to use the remote packages such ad importing "github.com/myrepo/mypackage". But I dont want to use remote imports; I want to push all my files in a second moment.

Could you help me to better understand what is the way to have local imports between packages in Go language?

thanks in advance

The reason you're not supposed to use relative imports is that they don't work inside of $GOPATH. Get rid of the "relative" part of your import paths, since all imports are relative to $GOPATH/src

import (
    "pack1"
    "router"
)

You will also want to move your Main.go into a package as well, so you you can make full use of the go tools.

As JimB says, read through the 'How to write go code' link, specifically https://golang.org/doc/code.html#ImportPaths

  • All packages exist inside a directory tree starting at $GOPATH/src.
  • Import path is effectively the full path to the package (from 1)
  • There are no sub packages in GO.
  • main packages are used to create commands

So in your case, your import paths will be "pack1" and "router"