likes
comments
collection
share

搭建 Go 语言的开发环境

作者站长头像
站长
· 阅读数 5

概述

我的工作电脑是 Windows 系统,开发环境主要使用虚拟机内的 Linux 系统。所以这里主要介绍 Linux 下 Go 环境的搭建,以及如何用 VS Code 连接虚拟机内的 Linux 系统进行开发。

下载 Go 安装包

Go 官方提供了不同操作系统、不同 CPU 架构下的安装包,我们可以在 go.dev/dl/ 手动下载并安装。 搭建 Go 语言的开发环境 如果想从源码构建安装可以按照 源码安装说明 去操作。 我们这里下载最新的 1.22.0 版本的 Linux amd64 安装包:

wget https://go.dev/dl/go1.22.0.linux-amd64.tar.gz

Linux 系统安装 Go

我们可以使用以下命令,删除以前安装的 Go,然后解压刚下载的安装包到 /usr/local 目录,Go 将被安装在 /usr/local/go 目录:

rm -rf /usr/local/go && tar -C /usr/local -xzf go1.22.0.linux-amd64.tar.gz

安装完成后将 /usr/local/go/bin~/go/bin 添加到环境变量 PATH 中:

export PATH=$PATH:/usr/local/go/bin:~/go/bin

注意,将此命令添加到 ~/.bashrc 配置文件中,使得下次启动终端也能生效:

echo 'export PATH=$PATH:/usr/local/go/bin:~/go/bin' >> ~/.bashrc

执行 go version 显示如下信息表示安装成功:

[root@dev100 ~]# go version
go version go1.22.0 linux/amd64

配置 Go 环境

在 Go 1.11 版本引入了“模块”概念,使用 go.mod 文件管理依赖版本(Go 1.11 之前版本中安装的依赖需存放在 $GOPATH/src 目录下):

go env -w GO111MODULE=on

This release adds preliminary support for a new concept called “modules,” an alternative to GOPATH with integrated support for versioning and package distribution. Module support is considered experimental, and there are still a few rough edges to smooth out, so please make liberal use of the issue tracker. -- Go 1.11 is released

更换代理提高下载模块速度:

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

配置 VS Code 开发

在 VS Code 中安装 Remote DevelopmentGo 插件:

搭建 Go 语言的开发环境

搭建 Go 语言的开发环境

通过 SSH 连接服务器,相当于 ssh root@192.168.192.100

搭建 Go 语言的开发环境

输入 >Go:Install/Update Tools 命令安装 VS Code 开发 Go 所需要的一些工具(语言服务、测试、debug、语法检查……)。

搭建 Go 语言的开发环境

勾选全部安装。

搭建 Go 语言的开发环境

安装完毕输出如下:

搭建 Go 语言的开发环境

我们可以在 $GOPATH 看到如下目录结构:

搭建 Go 语言的开发环境

bin:存放编译生成的可执行文件,一般 go install 会将编译生成的可执行文件存放在此。

pkg:存放下载的模块缓存。

现在可以使用 VS Code 开始开发模块了,先创建模块的目录并打开,初始化 helloWorld 模块:

go mod init helloWorld

新建 main.go 内容如下:

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()
    r.GET("/"func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{
            "message""Hello World!!!",
        })
    })
    r.Run(":60000")
}

安装 gin 依赖模块:

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

执行 go run main.go 运行模块,可以打开浏览器访问 http://192.168.192.100:60000/ 看到服务器返回的 "Hello World!!!" 。 在终端可以看到输出如下:

[root@dev100 helloWorld]# go run main.go 
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:   export GIN_MODE=release
 - using code:  gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET    /                         --> main.main.func1 (3 handlers)
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
[GIN-debug] Listening and serving HTTP on :60000
[GIN] 2024/02/21 - 15:01:47 | 200 |      46.685µs |   192.168.192.1 | GET      "/"