go modules 存在的意義是方便代碼的共享(雖然這會使本身開發過程當中有一些小小的麻煩)git
開發第一步,建立一個github倉庫,而後克隆到本地github
首先建立一個github倉庫github.com/<username>/hello
,這裏個人倉庫地址是:github.com/fudute/hello
。golang
而後在本地拉取遠程倉庫:shell
git clone https://github.com/fudute/hello.git cd hello
建立一個modulebash
go mod init github.com/fudute/hello
注意這裏的後綴要和github的網址一致函數
這會在當前目錄下建立一個go.mod文件,表示這是一個module。測試
而後建立一個文件hello.go:優化
package hello // Hello return "Hello World" func Hello() string { return "Hello World!" }
和測試文件hello_test.gocode
func TestHello(t *testing.T) { tests := []struct { name string want string }{ {name: "test", want: "Hello world!"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := Hello(); got != tt.want { t.Errorf("Hello() = %v, want %v", got, tt.want) } }) } }
如今進行測試:開發
> go test PASS ok example.com/hello 0.002s
說明功能沒有問題,這時候就能夠準備提交了。可是在提交以前,還存在一個版本問題
module的版本問題
版本的命名方式爲 vMAJOR.MINOR.PATCH
,有下面這些規則:
將module push到github上
先提交當前目錄下的文件:
git add * git commit -m "my first module"
須要先給module添加一個版本標記,指定版本爲 v0.1.0
git tag v0.1.0
而後push到github上
git push origin v0.1.0
建立另外一個項目,使用以前的module
接下來在本地建立一個main module
mkdir main cd main go mod init main
建立文件main.go
package main import ( "fmt" "github.com/fudute/hello" ) func main() { fmt.Println(hello.Hello()) }
在這裏導入了以前建立的module,路徑是github.com/fudute/hello
,而後直接運行:
> go run . go: extracting github.com/fudute/hello v0.1.0 Hello World!
能夠看到,golang會自動從github上拉取module,而後成功編譯運行。
自動下載的module能夠在$GOPATH/pkg/mod
目錄下看到。