John
John

Reputation: 1132

Importing custom packages in golang

I have the following:

app/main.go
app/server/server.go
app/server/templates.go

main.go has an import statement of import "app/server", but when compiled, it complains about:

found packages server (server.go) and templates (templates.go) in app/server

Im guessing it is confused about which package to load up? My intention is that server.go will setup the routes and import ./templates.go to render templates.

Is there a better way to layout files? Should I move templates.go to it's own directory?

Upvotes: 0

Views: 2259

Answers (1)

elithrar
elithrar

Reputation: 24300

Read this: http://golang.org/doc/code.html — but in short:

  • One package per directory/one directory per package. You have both server and templates packages where you should just have one - package main if you are attempting to compile a binary and not a library.

  • Don't use "relative" imports. Use the fully qualified path - i.e. if your base project is $GOPATH/src/github.com/JohnFromSO/myapp then you would import sub-packages as github.com/JohnFromSo/myapp/database.

  • You probably don't need to split out templates.go into a separate package - a good rule of thumb is "would this package be usable if it stood on its own/usable by others?"

Another good read is https://medium.com/@benbjohnson/structuring-applications-in-go-3b04be4ff091

Upvotes: 4

Related Questions