開發與維運

在 MacOS 上安装配置 Golang 开发环境

作者:雪梦科技

一、安装 Homebrew

打开终端,输入以下命令安装 Homebrew

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

二、安装配置 Golang

1. 通过 brew 方式安装 golang

在终端中输入以下命令安装 golang

brew install go

或者

brew install golang

2. 通过下载安装包,安装 golang

到官方网站 Downloads 下载golang软件安装包。
或者直接点击下面的链接,下载安装。
go1.12.9.darwin-amd64.pkg (121MB)



3. 配置 Goproxy 代理

由于众所周知的原因,下载 golang 相关模块非常困难。
这里介绍一种相对靠谱的解决方案:go mod + goproxy
通过编辑器打开 .bashrc 或者 .zshrc,将以下配置贴到文件最后,并保存。

# Enable the go modules feature
export GO111MODULE=on
# Set the GOPROXY environment variable
export GOPROXY=https://mirrors.aliyun.com/goproxy/

打开终端,输入以下命令使环境变量生效。

source .bashrc

或者

source .zshrc

三、 创建 HelloWorld 项目,验证 Golang

在终端输入以下命令,创建 HelloWorld 项目。
如果编译运行成功,则会打印出 "Hello, World!"

# 创建helloworld项目
mkdir helloworld
# 进入helloworld
cd helloworld
# 创建main.go 文件
cat>main.go<<EOF
package main
import "fmt"
func main() {
    fmt.Println("Hello, World!")
}
EOF
# 通过go mod 命令,初始化依赖文件
go mod init github.com/snowdreamtech/helloworld
# 编译,运行
go build main.go && ./main

Leave a Reply

Your email address will not be published. Required fields are marked *