14

golang使用Go Modules

 4 years ago
source link: https://studygolang.com/articles/26222
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

关于Go Modules

go modules是golang在v1.11版本开始支持的新型依赖管理系统,它的出现取代了$GOPATH/src,每个项目下仅使用一个go.mod文件管理依赖。

环境准备

0 . golang v1.11+版本

1 . 终端命令 go env -w GO111MODULE=on 开启go modules功能。

2 . 设置GOPROXY,针对默认代理proxy.golang.org被墙的问题。

go env -w GOPROXY=https://goproxy.cn,direct

3 . 设置GONOPRIVATE,针对公司内网代码无法拉取的问题,同时会默认设置GONOPROXY和GONOSUMDB。

go env -w GOPRIVATE=*.公司内网代码仓库域名,如*.qq.com

示例

go mod 命令

命令 说明 download 下载依赖包 edit 编辑go.mod graph 打印模块依赖图 init 初始化项目依赖 tidy 移除无用依赖 vendor 将依赖打包到vendor verify 核验依赖的正确性

0 . 目录结构:

project
.
└── main
    └── json.go
└── go.mod

1 . 初始化项目依赖

在项目根目录下执行 go mod init project

2 . 新增项目依赖

执行 go get github.com/json-iterator/go ,后面可接对应版本号,如 go get github.com/json-iterator/[email protected]

3 . 编写项目代码/main/json.go

package main  
  
import (  
   "fmt"  
   jsoniter "github.com/json-iterator/go"  
)  
  
const (  
   RED = iota  
   WHITE  
)  
  
type Moon struct {  
   Left int  
   Right int  
}  
  
func main() {  
   moon := &Moon{  
      Left:  RED,  
      Right: WHITE,  
   }  
   moonJsonStr, err := jsoniter.Marshal(moon)  
   if err != nil {  
      fmt.Println(err.Error())  
      return  
   }  
   fmt.Println(string(moonJsonStr))  
   //or  
   //fmt.Println(*(*string)(unsafe.Pointer(&moonJsonStr)))}

4 . 执行 go run main/json.go
参考链接: https://blog.golang.org/using-go-modules


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK