关于程序员:112GPT教学window安装go121的powershell脚本

3次阅读

共计 2353 个字符,预计需要花费 6 分钟才能阅读完成。

在 Windows 电脑上装置 Go 1.21

本文将介绍如何在 Windows 电脑上装置 Go 1.21,并配置罕用设置和工具,包含卸载之前的 Go 版本、装置地位、GOPATH、环境变量设置、dlv 的装置和中国境内代理设置。

筹备工作

在开始装置之前,请确保进行以下筹备工作:

  • 曾经在零碎上装置了 PowerShell
  • 曾经有其余版本的 Go,须要卸载之前的版本

卸载之前的 Go 版本

如果你之前曾经装置了其余版本的 Go,并想要卸载它们,请依照以下步骤进行:

  1. 创立一个名为 uninstall_go.ps1 的 PowerShell 脚本文件,并将以下内容粘贴进去:
$uninstallVersions = @("1.20", "1.19")  # 填写你要卸载的版本号,能够有多个
$goInstallDir = "D:\Tools\Go\Env\"  # Go 装置目录的门路

foreach ($version in $uninstallVersions) {
    $versionInstallDir = $goInstallDir + "go" + $version

    Write-Host "Uninstalling Go $($version)..."
    
    Remove-Item -Recurse -Force $versionInstallDir

    Write-Host "Go $($version) has been successfully uninstalled."
}
  1. 依据你须要卸载的版本号,在 $uninstallVersions 数组中填入相应的版本号。
  2. 运行 uninstall_go.ps1 脚本,它将顺次卸载每个版本的 Go。
PS C:\> .\uninstall_go.ps1

装置 Go 1.21

接下来,咱们将装置 Go 1.21。依照以下步骤进行操作:

  1. 下载安装脚本:

    将以下内容保留为 install_go.ps1 文件:

$goVersion = "1.21"
$goOS = "windows"
$goArch = "amd64"
$dlvVersion = "1.7.0"
$goPkg = "https://golang.org/dl/go$goVersion.$goOS-$goArch.zip"
$goInstallDir = "D:\Tools\Go\Env\go$goVersion"
$goPath = "D:\Tools\Go\GOPATH"
$env:Path += ";$goPath\bin"

Write-Host "Installing Go $($goVersion)..."

curl --silent --show-error --output go.zip $goPkg

if ($LASTEXITCODE -ne 0) {Write-Host "Failed to download Go $($goVersion). Please check your internet connection and try again."
    exit 1
}

Write-Host "Extracting Go $($goVersion)..."
Expand-Archive -Force -Path .\go.zip -DestinationPath $goInstallDir

if ($LASTEXITCODE -ne 0) {Write-Host "Failed to extract Go $($goVersion). Please make sure you have write permission for the installation directory ($goInstallDir) and try again."
    exit 1
}

[System.Environment]::SetEnvironmentVariable("GOPATH", $goPath, "Machine")
[System.Environment]::SetEnvironmentVariable("Path", "$env:Path;$($goInstallDir)\bin", "Machine")
[System.Environment]::SetEnvironmentVariable("GOROOT", $goInstallDir, "Machine")

Write-Host "Go $($goVersion) has been successfully installed."
  1. 运行装置脚本:

    在 PowerShell 中运行以下命令:

PS C:\> .\install_go.ps1

配置环境变量和设置代理

装置实现后,还须要进行一些配置,以确保 Go 失常运行。

配置 GOPATH 环境变量

  1. 关上控制面板,搜寻并点击“零碎”。
  2. 点击“高级零碎设置”。
  3. 在“零碎属性”对话框中,点击“环境变量”按钮。
  4. 在“零碎变量”区域中,点击“新建”。
  5. 输出变量名为 GOPATH,变量值为 D:\Tools\Go\GOPATH

配置 PATH 环境变量

  1. 在“零碎变量”区域中,找到名为 Path 的变量,并点击“编辑”。
  2. 在弹出的对话框中,点击“新建”。
  3. 输出变量值为 %GOPATH%\bin,点击“确定”。
  4. 确保此时已勾选“用户变量”区域下的“Path”变量,并点击“确定”。

设置代理

为了减速下载 Go 的依赖包,你能够设置中国境内的代理。在 PowerShell 中运行如下命令:

$env:GO111MODULE = "on"
$env:GOPROXY = "https://goproxy.io,direct"

这样就会应用 goproxy.io 这个代理来下载 Go 相干的依赖包。

运行 Go

当初,你曾经胜利装置了 Go 1.21,并配置好了相干的环境变量和代理。能够在命令行中输出 go version 命令来验证装置是否胜利。

PS C:\> go version

至此,你曾经实现了在 Windows 电脑上装置 Go 1.21 的过程。心愿本文对你有所帮忙!如果你有任何问题,请随时发问。

本文由 mdnice 多平台公布

正文完
 0