Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Developing Golang Package, cannot use relative path

Tags:

import

package

go

I'm trying to develop a simple golang package

let's say its name is "Hello", the directory structure is like below

hello
   games
   game-utils

then in hello.go (the main code) I have these:

import (
    gameUtils "./game-utils"
    "./games"
)

ok this worked well until I push to remote repo(e.g github.com) and try to use go get to install it. The problem was with the import path, I must change it to

import (
    gameUtils "github.com/user/hello/game-utils"
    "github.com/user/hello/games"
)

the question is, everytime I develop the package I cannot import using "github.com/user/hello/game-utils" because obviously I wouldn't have pushed it to the remote repo, I need to import it using "./game-utils".

Is there any elegant way to fix this issue?

like image 821
sendy halim Avatar asked Sep 11 '25 02:09

sendy halim


1 Answers

Read this.

You should always import it using:

import "github.com/user/hello/game-utils"

This is because of how the go tool works. It will look for it on the local machine in the directory: "GOPATH/src/github.com/user/hello/game-utils". As @JimB points out, the compiler always works with the local sources and the import paths are relative to GOPATH/src.

The go get tool is the only one that looks for the sources on the internet. After getting them, it downloads them to "GOPATH/src/IMPORT_PATH" so the compiler and the other tools can now see them in their local structure.

If you are creating a new project you should respect the same directory structure. If you are planning to upload your code to github then create manually the folder "GOPATH/src/github.com/YOUR-GITHUB-USER/PROYECT-NAME" and then initialize your git repo in there. (This works at least on git, hg, svn and github, bitbucket and google code)

like image 110
Topo Avatar answered Sep 13 '25 07:09

Topo