Go - go module 初始化及安裝 gin

Gin 是一個 Golang 網頁架構,具有相當好的效能,高於 httprouter 40 倍的速度,是一個兼具效能與實用的架構。

這裡首先會針對 go module 初始化 如何透過 Go Module 管理套件,以及說明如何透過 Go Module 安裝 gin 的流程。

初始化 go module

手動啟用 go module ,讓 go module 可以在 GOPATH 以外的地方直接運作

export GO111MODULE=on

初始化 go module

go mod init myapp

//go: creating new go.mod: module myapp

安裝

在使用 Gin 架構必須是 Go 1.10 以上版本。

(如果沒有使用 go module ,就需要手動下載 gin: ```go

用 import 方式直接帶入

CVT2HUGO: get -u github.com/gin-gonic/gin```)
import "github.com/gin-gonic/gin"

如果需要使用到 http.StatusOK 之類的功能,則可以載入 net/http

(選擇性)

import "net/http"

當接續執行 go build 或 go test 就會自動將 gin 下載,並且自動記錄在 go.mod

透過以下指令可以查詢目前安裝的 dependencies

go list -m all

啟動

這裡直接下載官方範例

curl https://raw.githubusercontent.com/gin-gonic/examples/master/basic/main.go > main.go

接著啟用

go build main.go
./main

這時可能會有系統提示,直接允許運行

接著開啟瀏覽器前往 http://localhost:8080/ping

應該會看到 pong

最後,確認一下 go.mod ,會看到自動加載 gin

cat go.mod

升級或降級依賴

可以直接透過 go get 方式進行升降級,這動作將會自動更新 go.mod

也可以透過手動編輯 go. mod 方式。

執行 go build 或 go test 就可以直接升級

升級後可以查看目前的 module

go list -u -m all

問題排解

問題一、

cannot find package “github.com/gin-gonic/gin” in any of: /usr/local/go/src/github.com/gin-gonic/gin (from $GOROOT) /Users/liaoxiangru/go/src/github.com/gin-gonic/gin (from $GOPATH)

發生錯誤原因在於找不到 gin package,重新下載應該就會正常

go get -u github.com/gin-gonic/gin

問題二、

go: cannot determine module path for source directory /Users/xxxx (outside GOPATH, no import comments)

原因在於 go mod init 沒有指定名稱,嘗試加上名稱就會正常

go mod init my-mod-test