Istvan
Istvan

Reputation: 8562

How to import local files in Go?

I would like to organize my Go code into smaller chunks. Lets assume I am writing a web application that follows the MVC pattern. I would like to organize my code like this:

main.go
controllers/whatever/whatever.go
models/whateverelse/whateverelse.go

And than in main.go I would like to:

import "controllers/whatever"

Is this possible with Go? It seems the only option, that does not make too much sense is to put the the files into the GOPATH/src folder. In that case I need to set the git repository to track the $GOPATH/ instead of just tracking my project that is $GOPATH/src/github/username/project.

Upvotes: 3

Views: 10645

Answers (2)

Mingyu
Mingyu

Reputation: 33359

The solution you have could definitely work if you have the standard github directory structure. However, I would like to point out that to import a go library, you just need to specify the path to that library starting from the directory below src.

If your project library has the path:

src/yourproject1/controllers

and your main code has the path:

src/yourproject2/main.go

In main.go, you simply need to say:

import "yourproject1/controllers"

Upvotes: 3

Istvan
Istvan

Reputation: 8562

The solution came from IRC thanks to jaw22:

import "github.com/yoursuername/yourproject/yourlib"

Upvotes: 2

Related Questions