imranhasanhira
imranhasanhira

Reputation: 357

How to import project specific go packages while maintaining a separate location for go packages that are common to totally different projects?

So I was developing a go application for the very first time. I came to know that there are two variables GOROOT and GOPATH which are used to maintain go packages. What I understand till now, is that GOROOT is for the go binary files and GOPATH is mainly for storing library and helper packages that is needed for projects.

Here is my current project structure -

/Users/john/work/project-mars
/Users/john/work/project-mars/main.go
/Users/john/work/project-mars/helper
/Users/john/work/project-mars/helper/helper.go

Content of main.go

package main

import (
    "fmt"
    "helper"
)

func main(){
    fmt.Println("Hello")
}

Content of helper.go

package helper

import (
    "fmt"
)

func SayWorld(){
    fmt.Println("World")
}

And the go variables are -

GOROOT = /Users/john/apps/go
GOPATH = /Users/john/apps/go-packages

Problem: Now when I perform the following command, I get this error -

mac-machine:project-mars john$ go build main.go 
main.go:5:5: cannot find package "helper" in any of:
    /Users/john/apps/go/src/helper (from $GOROOT)
    /Users/john/apps/go-packages/src/helper (from $GOPATH)

I understand that GOPATH should be the project directory that I am working on. But I am concerned with keeping my projects and library packages in a modular way, so that when later I have a totally different project (i.e. project-aurora) which might use same github helper packages, that they are not downloaded two times, both in project-mars and project-aurora .

How can I avoid this redundancy while working on different projects ?

Update: It's not that I can not compile them. I can use the GOPATH as my project directory and use src,pkg,bin project layouts and also reorganize the files and finally get to compile the project. yeeeeppi. But my question is about resolving the redundancy of common package problem that appears in this single GOPATH way.

Upvotes: 1

Views: 967

Answers (2)

Mr_Pink
Mr_Pink

Reputation: 109405

Please read How to Write Go Code carefully. It explains everything you need to know.

You don't use GOPATH as your project directory. Assuming you want to work with the standard Go tooling, your package source needs to be in the directory corresponding to its import path, just like any other package.

Your project should be located at $GOPATH/src/project-mars, which can be built via go install project-mars. The helper package should be located at $GOPATH/src/project-mars/helper, and imported via "project-mars/helper".

Upvotes: 1

Zee
Zee

Reputation: 840

Rename your helper-lib folder to helper

Then move this folder from project-mars to the upper folder work

This should make your

import "helper" 

statement in main.go work.

Upvotes: 0

Related Questions