蓝色天空.知识 · 实践 · 创造
我的收藏
Go 教程目录 33章
Go / LEARN BY DOING

Go 语言环境安装

介绍 Go 支持的操作系统平台、官方安装包命名规则、UNIX/Linux/macOS 与 Windows 下的安装与 PATH 配置步骤,并在本地 Go 1.22.12 容器实测 GOROOT、PATH 与 test.go 执行。

学完这一章,你能够

  • 介绍 Go 支持的操作系统平台、官方安装包命名规则、UNIX/Linux/macOS 与 Windows 下的安装与 PATH 配置步骤,并在本地 Go 1.22.12 容器实测 GOROOT、PATH 与 test.go 执行。

支持平台与官方安装包选型

Go 官方工具链原生支持 Linux、FreeBSD、macOS(即 Mac OS X / Darwin)与 Windows 等主流操作系统。安装包可从 Go 官方网站 `https://go.dev/dl/` 获取,国内网络访问受限时也可使用官方镜像站 `https://golang.google.cn/dl/`。选择安装包时需核对操作系统与处理器架构(如 x86-64 的 `amd64` 或 Apple Silicon 的 `arm64`),下方参考表以 `go1.26.3` 为例列出了各平台对应包名与系统要求。

UNIX / Linux / macOS / FreeBSD 安装与 PATH 配置

在 Linux、FreeBSD 等类 UNIX 系统中,通常采用官方二进制压缩包部署(历史上文档常以 `go1.4.linux-amd64.tar.gz` 示例,实际安装请选用最新稳定版本号):先下载对应架构的 `.tar.gz` 压缩包,再通过 `tar -C /usr/local -xzf <archive>.tar.gz` 解压至 `/usr/local`(覆盖升级前建议先清理旧 `/usr/local/go`),随后将 `/usr/local/go/bin` 加入 `PATH`:`export PATH=$PATH:/usr/local/go/bin`。

直接在终端运行 `export` 仅对当前会话有效,关闭终端后即会失效。若要永久生效,应将 `export PATH=$PATH:/usr/local/go/bin` 追加至 `~/.bash_profile`(使用 Zsh 的 macOS 环境为 `~/.zshrc`)或系统级 `/etc/profile` 末尾,并执行 `source ~/.bash_profile` 或 `source /etc/profile` 立即加载。在 macOS 下,也可直接双击 `.pkg` 图形安装包完成部署,默认安装路径同样为 `/usr/local/go/`。

Windows 安装与环境验证测试

在 Windows 系统中,推荐下载 `.msi` 图形化安装程序(例如 `go1.26.3.windows-amd64.msi` 或旧版示例 `go1.4.2.windows-amd64.msi`)。早期版本默认安装于 `C:\Go`(新版 `.msi` 默认安装至 `C:\Program Files\Go`),若安装程序未自动写入环境变量,可手动将对应 `bin` 目录(如 `C:\Go\bin`)加入系统 `Path`,并重新打开命令提示符窗口使其生效。

安装完成后,可新建工作目录(如 Windows 下的 `C:\Go_WorkSpace`),编写包含 `package main`、`import "fmt"` 与 `fmt.Println("Hello, World!")` 的 `test.go` 文件,执行 `go run test.go` 检验环境。本站离线实验已核验 5 类安装包命名规律、容器内 `GOROOT` 与 `PATH` 检出状态,并在临时工作目录实测 `go run test.go` 精确输出 `Hello, World!`。

各操作系统官方 Go 安装包命名与要求参考表

安装包文件名适用系统处理器架构系统版本要求说明
go1.26.3.windows-amd64.msiMicrosoft Windowsx86-64 (Intel 64-bit)Windows 10 或更新Windows 64 位图形化安装程序。
go1.26.3.darwin-arm64.pkgApple macOSARM64 (Apple Silicon 64-bit)macOS 12 或更新适用于搭载 Apple M 系列芯片的 Mac 安装包。
go1.26.3.darwin-amd64.pkgApple macOSx86-64 (Intel 64-bit)macOS 12 或更新适用于搭载 Intel 处理器的传统款 Mac 安装包。
go1.26.3.linux-amd64.tar.gzLinuxx86-64 (Intel 64-bit)Linux 3.2 或更新面向绝大多数 64 位 Linux 发行版的二进制压缩包。
go1.26.3.src.tar.gz任意系统源码-Go 语言完整源代码包,供自行构建编译使用。

校验多平台安装包分类、环境变量 PATH/GOROOT 与 test.go 执行

含完整源码 · 156 行
展开查看收起
go
package main

import (
	"encoding/json"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"reflect"
	"runtime"
	"strings"
)

type CaseResult struct {
	Name     string `json:"name"`
	Summary  string `json:"summary"`
	Expected any    `json:"expected"`
	Actual   any    `json:"actual"`
	Passed   bool   `json:"passed"`
}

type LabOutput struct {
	Version string       `json:"version"`
	Cases   []CaseResult `json:"cases"`
}

func makeCase(name, summary string, expected, actual any) CaseResult {
	return CaseResult{
		Name:     name,
		Summary:  summary,
		Expected: expected,
		Actual:   actual,
		Passed:   reflect.DeepEqual(expected, actual),
	}
}

func classifyArchive(filename string) string {
	switch {
	case strings.HasSuffix(filename, ".msi"):
		return "windows-installer"
	case strings.HasSuffix(filename, ".pkg"):
		return "macos-pkg"
	case strings.Contains(filename, ".src."):
		return "source-tarball"
	case strings.HasSuffix(filename, ".tar.gz"):
		return "unix-binary-tarball"
	default:
		return "unknown"
	}
}

func main() {
	var cases []CaseResult

	// 1. platform_package_naming
	files := []string{
		"go1.26.3.windows-amd64.msi",
		"go1.26.3.darwin-arm64.pkg",
		"go1.26.3.darwin-amd64.pkg",
		"go1.26.3.linux-amd64.tar.gz",
		"go1.26.3.src.tar.gz",
	}
	kinds := make([]string, 0, len(files))
	for _, f := range files {
		kinds = append(kinds, classifyArchive(f))
	}
	cases = append(cases, makeCase(
		"platform_package_naming",
		"校验 Windows、macOS (ARM64/AMD64)、Linux 与源码包命名后缀分类",
		[]string{"windows-installer", "macos-pkg", "macos-pkg", "unix-binary-tarball", "source-tarball"},
		kinds,
	))

	// 2. unix_path_and_env_inspection
	goRootOut, err := exec.Command("go", "env", "GOROOT").CombinedOutput()
	if err != nil {
		panic(err)
	}
	goroot := strings.TrimSpace(string(goRootOut))
	pathEnv := os.Getenv("PATH")
	hasGoBin := false
	for _, seg := range strings.Split(pathEnv, string(os.PathListSeparator)) {
		if strings.HasSuffix(seg, "/go/bin") || seg == filepath.Join(goroot, "bin") {
			hasGoBin = true
			break
		}
	}
	unixExport := "export PATH=$PATH:/usr/local/go/bin"
	cases = append(cases, makeCase(
		"unix_path_and_env_inspection",
		"检测当前容器 GOROOT、PATH 中 Go 可执行目录及 UNIX 环境变量导出语句",
		map[string]any{
			"goroot_non_empty": true,
			"path_has_go_bin":  true,
			"export_contains":  true,
			"goos_goarch":      "linux/amd64",
		},
		map[string]any{
			"goroot_non_empty": goroot != "",
			"path_has_go_bin":  hasGoBin,
			"export_contains":  strings.Contains(unixExport, "/usr/local/go/bin"),
			"goos_goarch":      runtime.GOOS + "/" + runtime.GOARCH,
		},
	))

	// 3. windows_msi_path_rules
	winPath := `C:\Windows\System32;C:\Go\bin`
	segments := strings.Split(winPath, ";")
	cases = append(cases, makeCase(
		"windows_msi_path_rules",
		"验证 Windows 默认 .msi 安装路径 C:\\Go\\bin 在 Path 列表中的拆分与定位",
		map[string]any{
			"segment_count": 2,
			"go_bin_entry":  `C:\Go\bin`,
		},
		map[string]any{
			"segment_count": len(segments),
			"go_bin_entry":  segments[1],
		},
	))

	// 4. test_go_execution
	tmpDir, err := os.MkdirTemp("", "golab-env-*")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(tmpDir)

	testGo := filepath.Join(tmpDir, "test.go")
	code := "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfmt.Println(\"Hello, World!\")\n}\n"
	if err := os.WriteFile(testGo, []byte(code), 0o600); err != nil {
		panic(err)
	}
	outBytes, err := exec.Command("go", "run", testGo).CombinedOutput()
	if err != nil {
		panic(fmt.Sprintf("go run test.go failed: %v: %s", err, string(outBytes)))
	}
	cases = append(cases, makeCase(
		"test_go_execution",
		"在临时工作目录编写 test.go 并通过 go run test.go 验证安装环境输出",
		"Hello, World!",
		strings.TrimSpace(string(outBytes)),
	))

	out := LabOutput{
		Version: fmt.Sprintf("%s %s/%s", runtime.Version(), runtime.GOOS, runtime.GOARCH),
		Cases:   cases,
	}
	enc := json.NewEncoder(os.Stdout)
	enc.SetEscapeHTML(false)
	enc.SetIndent("", "  ")
	if err := enc.Encode(out); err != nil {
		panic(err)
	}
}
5 类安装包后缀分类准确,当前 Go 容器 GOROOT 与 PATH 检出正常,Windows Path 拆分正确,且临时工作目录运行 test.go 输出 Hello, World!。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1159.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Go

课程关联工程包(登记关联33章) · 含当前章节或实例 · mbskycom202612a1159.zip

下载课程关联工程包:Go

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1165.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

因为命令行直接执行 `export` 只修改当前 Shell 进程及其子进程的环境变量;必须将该语句写入 `~/.bash_profile`、`~/.bashrc`、`~/.zshrc` 或 `/etc/profile` 并用 `source` 重载才能持久化生效。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习