Here is my main file (server.go):
package main
import (
"net/http"
"routes"
)
func main() {
http.HandleFunc("/", routes.Handler)
http.ListenAndServe(":8000", nil)
}
My routes module is in the same directory:
package routes
func Handler(w http.ResponseWriter, r *http.Request) {
// stuff...
}
When I run go run server.go
I get this error:
server.go:6:5: cannot find package "routes" in any of:
/usr/local/Cellar/go/1.6/libexec/src/routes (from $GOROOT)
~/server/src/routes (from $GOPATH)
When I place the code in routes.go
into my server.go
file, it runs fine. I cannot import the module. I have tried setting the $GOPATH
variable to my current directory, I've tried rearranging my project directory to mimic the one here. I'm running out of options. It is strange that a language with such wide adoption has such poor documentation on how to do something that is relatively easy in almost every other language. Please help me figure out what I'm doing wrong.
This is the output of go env
GOARCH="amd64"
GOBIN=""
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH="/Users/me/server"
GORACE=""
GOROOT="/usr/local/Cellar/go/1.6/libexec"
GOTOOLDIR="/usr/local/Cellar/go/1.6/libexec/pkg/tool/darwin_amd64"
GO15VENDOREXPERIMENT="1"
CC="clang"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fno-common"
CXX="clang++"
CGO_ENABLED="1"
Move the routes package to /Users/me/server/src/routes
and you should be good to go.
The "How To Write Go Code" article is the recommended starting point right on the Getting Started page which explains this. (thanks @elithrar)
Peter Bourgon has a good write up on well structured Go applications.
You should either have the routes
package in a routes
folder, or if your main package is in the routes folder you can have a lib
folder within that folder with your actual routes
package.
The reason for the folder structure is due to how go import
statements work. It would be ambiguous to enable multiple packages in the same folder given the way imports work.