Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import local files in Go?

Tags:

import

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.

like image 946
Istvan Avatar asked Oct 18 '25 12:10

Istvan


1 Answers

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"
like image 173
Mingyu Avatar answered Oct 21 '25 11:10

Mingyu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!