# Golang go mod 入門

Go mod 是 go 1.11 version 之後出的管理套件的工具，並且Go 1.13 version 之後成為管理套件的正式工具(成為default)。

> [**範例程式碼**](https://github.com/XiXiangFiles/golang-mod-tutorial)

### GOPATH使用方式(早期使用方式)

在go mod 發布之前都是需要在$GOPATH/src路徑下才能夠使用，當需要使用模組的時候，必須將用到的資料夾link 到$GOPATH/src才能夠使用。

![查看GOPATH](https://cdn-images-1.medium.com/max/800/1*NlGvZE7s94dGJb-66tOLWQ.png)

以上圖為例，如果要使用模組需確保/home/ubuntu/go/src中有該模組才能夠取用。下面舉hello world實例。

檔案結構： **執行go run main.go 印出 hello world**

```
-hello_GOPATH/
   - main.go
   - src/
   - hello/
       - hello.go
```

step 1. 將GOPATH指到目前資料夾

```
go env -w GOPATH=$(pwd)
```

![確認GOPATH位置](https://cdn-images-1.medium.com/max/800/1*UM8DBOaia3PFqnENWT9MWw.png)

step 2. 撰寫package hello 模組(package)

```go
package hello
import "fmt"
func PrintHello() { // fun大寫代表public(才能夠被存取)
    fmt.Println("hello world")
}
```

step 3. 將package資料夾link 到$GOPATH/src/

```
ln -s `pwd`/hello $(go env GOPATH)/src
```

step 4. 撰寫package main

```go
package main
import "hello"  // src/hello 資料夾下
func main() {
    hello.PrintHello()
}
```

執行結果：

![](https://cdn-images-1.medium.com/max/800/1*tSg_5Cab_q5r-jJjCu1LGQ.png)

### Go mod 使用方法

這種用法不用像使用GOPATH的方法，需要改變GOPATH的位置。而是透過go.mod檔案辨識目前要執行的專案位置(取代GOPATH設定)。並且go.mod可以紀錄所有使用的相依模組，只要透過go install指令就可以自動安裝所有相依模組的功能。

檔案結構： **執行go run main.go 印出 hello world**

```
-hello/
   - main.go
   - go.mod
   - hello/
       - hello.go
```

step 1. go mod init hello

![](https://cdn-images-1.medium.com/max/800/1*v01xFqsBXp0vDJVfj-aS9g.png)

```
module hello  //產生出來的模組名
go 1.15 // golang 現在的版本
```

step 2. 撰寫hello 模組

```go
package hello
import "fmt"
func PrintHello() { // fun大寫代表public(才能夠被存取)
    fmt.Println("hello world")
}
```

step 3. 撰寫package main(需要在最上層)

```go
package main
import "hello/hello"  //module/package name
func main() {
    hello.PrintHello()
}
```

執行結果：

![](https://cdn-images-1.medium.com/max/800/1*bcNrwG5CpKdGNE-a_CY27g.png)

> v1.11之後為了解決套件管理的問題，官方出現了go mod的工具，並且v1.11、v1.12可以共存GOPATH的存在。然而在1.13之後GOPATH跟go mod**兩者是不能並存的 (GOPATH不可指向有go.mod 的資料夾)** 。

### 總結

在撰寫Golang 專案的時候，盡量的使用go mod，盡量不修改GOPATH來開發。因為go mod會幫助開發者紀錄相依的模組，方便之後部署、交付程式碼。

## 參考資料

<https://blog.golang.org/using-go-modules>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://xiang753017.gitbook.io/zixiang-blog/golang/golang-go-mod-ru-men.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
