一、go mod安裝
1、為什麼要安裝go mod
在專案中需要某個依賴包,必須使用go get安裝,否則執行go run main.go會報錯。這種方式在依賴包較多時不便於管理,於是在go1.11版本就有了go mod。go mod是go的包管理工具,使用go mod後,無需把所有專案放在$GOPATH/src,專案可以放在任何位置
go get有時下載某個外掛的時候需要FQ,如果你的電腦沒有FQ的話是安裝不上去的,比如:go get -u github.com/gin-gonic/gin,,因為它有連線到google的檔案,所以我們需要配置go mod,當然你也可以FQ。
2、 go mod安裝
第一步:在環境變數中配置環境變數
export GO111MODU=on
export GOPROXY=https://goproxy.io
配置好以後讓配置生效
source ~/.bash_profile
第二步:在idea中配置啟用go module

新增環境變數


配置好了。
3. 使用go mod建立專案
go mod init 專案名
在src目錄下,我們建立一個叫api的專案
mkdir api
在根目錄下執行
go mod init api
會看到如下輸出
go: creating new go.mod: module api
go: to add module requirements and sums:
go mod tidy
表示module初始化成功了,在目錄下生成go.mod檔案。
包含go.mod檔案的目錄稱為模組根,go.mod 檔案的出現定義了它所在的目錄為一個模組,該模組下的模組匯入其他模組都以它為參照,如import api/xxx
一、gin安裝
第一步:下載gin
下載之前要配置好環境變數和go mod,不然可能下載不下來
go get -u github.com/gin-gonic/gin

第二步:簡單的http請求
1.新建一個hello專案
2.在專案下新增hello.go檔案,檔案內容如下:
package main
import "github.com/gin-gonic/gin"
func main() {
// gin.Default()是例項化一個預設的gin示例,便於我們操
r := gin.Default()
// 註冊一個GET訪問處理函式,路徑是根路徑
r.GET("/", func(c *gin.Context) {
c.JSON(200, gin.H{
"name":"zhangsan",
"age":"24",
})
})
r.Run(":8080")
}
檔案編譯報錯, 執行go mod tidy下載缺失的外掛即可。
3.然後我們執行它,開啟瀏覽器,輸入http://localhost:8080/
就可以看到如下內容:
{
"age": "24",
"name": "zhangsan"
}
至此,gin已經能夠正常的跑起來了。