Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang import path best practice

Tags:

import

go

I am currently working on a private project using Golang (and I am new to it).

But I have the problem that I don't know what is the proper way to define the import path for local packages.

I have the same feeling as the author from this link https://medium.com/@c9s/golang-the-annoying-remote-import-path-c6c7e76517e5

In short, if I host a project foo in Github. I feel strange to use github.com/levin/foo as import path instead of just foo. Wouldn't it cause much rework if I move my codes to Bitbucket or I host my own git server in AWS?

And worse, I can rewrite my code to change the import path, but how would people using my code in theirs notify the change of repo? And I feel no sense to ask others to update their codes.

I am new to Golang so feel free to say something like "your question is not even valid".

like image 698
Levin Kwong Avatar asked Sep 20 '17 03:09

Levin Kwong


Video Answer


1 Answers

This question should probably be re-answered as of Go 1.11 with the introduction of Go Modules. Modules can be used to solve this "local path" dilemma as well as pesky projects outside the scope of GOPATH. You may now initialize your project via...

go mod init <main package name>

You may then reference a local package by their package name. Like this...

go mod init app

Then (assuming you have another local package called "models") reference within your file

import (
  "app/models"
)

Refs:

https://github.com/golang/go/wiki/Modules

Accessing local packages within a go module (go 1.11)

like image 164
Nicholas Siebenaller Avatar answered Sep 29 '22 23:09

Nicholas Siebenaller