如何在Ubuntu 18.04上安装Go并设置本地编程环境

介绍 (Introduction)

Go is a programming language that was born out of frustration at Google. Developers continually had to pick a language that executed efficiently but took a long time to compile, or to pick a language that was easy to program but ran inefficiently in production. Go was designed to have all three available at the same time: fast compilation, ease of programming, and efficient execution in production.

Go是一种编程语言,它源于Google的无奈之举。 开发人员不断不得​​不选择一种执行效率高但编译时间长的语言,或者选择一种易于编程但在生产中运行效率低下的语言。 Go旨在同时提供所有三个功能:快速编译,易于编程以及在生产中高效执行。

While Go is a versatile programming language that can be used for many different programming projects, it’s particularly well suited for networking/distributed systems programs, and has earned a reputation as “the language of the cloud”. It focuses on helping the modern programmer do more with a strong set of tooling, removing debates over formatting by making the format part of the language specification, as well as making deployment easy by compiling to a single binary. Go is easy to learn, with a very small set of keywords, which makes it a great choice for beginners and experienced developers alike.

尽管Go是一种通用的编程语言,可以用于许多不同的编程项目,但它特别适合于网络/分布式系统程序,并赢得了“云语言”的美誉。 它着重于帮助现代程序员使用强大的工具集来做更多的事情,通过使格式成为语言规范的一部分来消除有关格式的争论,并通过编译为单个二进制文件使部署变得容易。 Go易于学习,只包含很少的关键字,对于初学者和经验丰富的开发人员而言,它都是不错的选择。

This tutorial will guide you through installing and configuring a programming workspace with Go via the command line. This tutorial will explicitly cover the installation procedure for Ubuntu 18.04, but the general principles can apply to other Debian Linux distributions.

本教程将指导您通过命令行使用Go安装和配置编程工作区。 本教程将明确涵盖Ubuntu 18.04的安装过程,但一般原则可适用于其他Debian Linux发行版。

先决条件 (Prerequisites)

You will need a computer or virtual machine with Ubuntu 18.04 installed, as well as have administrative access to that machine and an internet connection. You can download this operating system via the Ubuntu 18.04 releases page.

您将需要一台安装了Ubuntu 18.04的计算机或虚拟机,并且对该计算机和Internet连接具有管理权限。 您可以通过Ubuntu 18.04版本页面下载此操作系统。

第1步-设置Go (Step 1 — Setting Up Go)

In this step, you’ll install Go by downloading the current release from the official Go downloads page.

在此步骤中,您将通过从官方的Go下载页面下载当前版本来安装Go。

To do this, you’ll want to find the URL for the current binary release tarball. You will also want to note the SHA256 hash listed next to it, as you’ll use this hash to verify the downloaded file.

为此,您需要查找当前二进制发行版tarball的URL。 您还需要注意其旁边列出的SHA256哈希,因为您将使用此哈希来验证下载的文件

You’ll be completing the installation and setup on the command line, which is a non-graphical way to interact with your computer. That is, instead of clicking on buttons, you’ll be typing in text and receiving feedback from your computer through text as well.

您将在命令行上完成安装和设置,这是与计算机交互的非图形方式。 也就是说,您将不用输入按钮,而是输入文本,并通过文本接收来自计算机的反馈。

The command line, also known as a shell or terminal, can help you modify and automate many of the tasks you do on a computer every day, and is an essential tool for software developers. There are many terminal commands to learn that can enable you to do more powerful things. For more information about the command line, check out the Introduction to the Linux Terminal tutorial.

命令行,也称为外壳程序终端 ,可以帮助您修改和自动化每天在计算机上执行的许多任务,并且是软件开发人员的必备工具。 有许多要学习的终端命令,可以使您执行更强大的功能。 有关命令行的更多信息,请查看《 Linux Terminal简介》教程。

On Ubuntu 18.04, you can find the Terminal application by clicking on the Ubuntu icon in the upper-left hand corner of your screen and typing terminal into the search bar. Click on the Terminal application icon to open it. Alternatively, you can hit the CTRL, ALT, and T keys on your keyboard at the same time to open the Terminal application automatically.

在Ubuntu 18.04上,您可以通过单击屏幕左上角的Ubuntu图标,然后在搜索栏中键入terminal来找到Terminal应用程序。 单击终端应用程序图标以将其打开。 或者,您可以同时按下键盘上的CTRLALTT键以自动打开“终端”应用程序。

Once the terminal is open, you will manually install the Go binaries. While you could use a package manager, such as apt-get, walking through the manual installation steps will help you understand any configuration changes to your system that are needed to have a valid Go workspace.

打开终端后,您将手动安装Go二进制文件。 尽管可以使用apt-get等软件包管理器,但逐步执行手动安装步骤将帮助您了解拥有有效的Go工作区所需的系统配置更改。

Before downloading Go, make sure that you are in the home (~) directory:

在下载Go之前,请确保您位于主目录( ~ )中:

  • cd ~

    光盘〜

Use curl to retrieve the tarball URL that you copied from the official Go downloads page:

使用curl检索您从Go官方下载页面复制的tarball URL:

  • curl -O https://dl.google.com/go/go1.12.1.linux-amd64.tar.gz

    curl -O https://dl.google.com/go/ go1.12.1.linux-amd64 .tar.gz

Next, use sha256sum to verify the tarball:

接下来,使用sha256sum验证tarball:

  • sha256sum go1.12.1.linux-amd64.tar.gz

    sha256sum go1.12.1.linux-amd64 .tar.gz

The hash that is displayed from running the above command should match the hash that was on the downloads page. If it does not, then this is not a valid file and you should download the file again.

运行上述命令显示的哈希值应与下载页面上的哈希值匹配。 如果不是,则这不是有效文件,您应该再次下载该文件。


   
   
Output
2a3fdabf665496a0db5f41ec6af7a9b15a49fbe71a85a50ca38b1f13a103aeec go1.12.1.linux-amd64.tar.gz

Next, extract the downloaded archive and install it to the desired location on the system. It’s considered best practice to keep it under /usr/local:

接下来,解压缩下载的档案并将其安装到系统上的所需位置。 将其保存在/usr/local下被认为是最佳实践:

  • sudo tar -xvf go1.12.1.linux-amd64.tar.gz -C /usr/local

    须藤tar -xvf go1.12.1.linux-amd64 .tar.gz -C / usr / local

You will now have a directory called go in the /usr/local directory. Next, recursively change this directory’s owner and group to root:

现在,在/usr/local目录中将有一个名为go的目录。 接下来,递归地将该目录的所有者和组更改为root

  • sudo chown -R root:root /usr/local/go

    须藤chown -R root:root / usr / local / go

This will secure all the files and ensure that only the root user can run the Go binaries.

这将保护所有文件,并确保只有root用户才能运行Go二进制文件。

Note: Although /usr/local/go is the officially-recommended location, some users may prefer or require different paths.

注意 :尽管/usr/local/go是官方推荐的位置,但是某些用户可能更喜欢或需要不同的路径。

In this step, you downloaded and installed Go on your Ubuntu 18.04 machine. In the next step you will configure your Go workspace.

在此步骤中,您在Ubuntu 18.04计算机上下载并安装了Go。 在下一步中,您将配置Go工作区。

第2步-创建您的Go工作区 (Step 2 — Creating Your Go Workspace)

You can create your programming workspace now that Go is installed. The Go workspace will contain two directories at its root:

安装Go之后,您可以创建您的编程工作区。 Go工作空间的根目录将包含两个目录:

  • src: The directory that contains Go source files. A source file is a file that you write using the Go programming language. Source files are used by the Go compiler to create an executable binary file.

    src :包含Go源文件的目录。 源文件是您使用Go编程语言编写的文件。 Go编译器使用源文件来创建可执行的二进制文件。

  • bin: The directory that contains executables built and installed by the Go tools. Executables are binary files that run on your system and execute tasks. These are typically the programs compiled by your source code or other downloaded Go source code.

    bin :该目录包含由Go工具构建和安装的可执行文件。 可执行文件是在系统上运行并执行任务的二进制文件。 这些通常是由您的源代码或其他下载的Go源代码编译的程序。

The src subdirectory may contain multiple version control repositories (such as Git, Mercurial, and Bazaar). This allows for a canonical import of code in your project. Canonical imports are imports that reference a fully qualified package, such as github.com/digitalocean/godo.

src子目录可能包含多个版本控制存储库(例如GitMercurialBazaar )。 这允许在项目中规范地导入代码。 规范导入是引用完全合格的软件包的导入,例如github.com/digitalocean/godo

You will see directories like github.com, golang.org, or others when your program imports third party libraries. If you are using a code repository like github.com, you will also put your projects and source files under that directory. We will explore this concept later in this step.

你会看到这样的目录github.comgolang.org ,或者别人当你的程序导入第三方库。 如果您使用的是github.com类的代码存储库,还将把项目和源文件放在该目录下。 我们将在此步骤的稍后部分探讨这个概念。

Here is what a typical workspace may look like:

这是典型的工作空间可能看起来像:

.
├── bin
│   ├── buffalo                                      # command executable
│   ├── dlv                                          # command executable
│   └── packr                                        # command executable
└── src
    └── github.com
        └── digitalocean
            └── godo
                ├── .git                            # Git repository metadata
                ├── account.go                      # package source
                ├── account_test.go                 # test source
                ├── ...
                ├── timestamp.go
                ├── timestamp_test.go
                └── util
                    ├── droplet.go
                    └── droplet_test.go

The default directory for the Go workspace as of 1.8 is your user’s home directory with a go subdirectory, or $HOME/go. If you are using an earlier version of Go than 1.8, it is still considered best practice to use the $HOME/go location for your workspace.

从1.8开始,Go工作区的默认目录是用户的主目录,其中带有go子目录,即$HOME/go 。 如果您使用的Go版本早于1.8,则仍然将$HOME/go位置用于工作区仍然是最佳实践。

Issue the following command to create the directory structure for your Go workspace:

发出以下命令为您的Go工作区创建目录结构:

  • mkdir -p $HOME/go/{bin,src}

    mkdir -p $ HOME / go / {bin,src}

The -p option tells mkdir to create all parents in the directory, even if they don’t currently exist. Using {bin,src} creates a set of arguments to mkdir and tells it to create both the bin directory and the src directory.

-p选项告诉mkdir在目录中创建所有parents ,即使它们当前不存在也是如此。 使用{bin,src}mkdir创建一组参数,并告诉它创建bin目录和src目录。

This will ensure the following directory structure is now in place:

这将确保以下目录结构到位:

└── $HOME
    └── go
        ├── bin
        └── src

Prior to Go 1.8, it was required to set a local environment variable called $GOPATH. $GOPATH told the compiler where to find imported third party source code, as well as any local source code you had written. While it is no longer explicitly required, it is still considered a good practice as many third party tools still depend on this variable being set.

在Go 1.8之前,需要设置一个名为$GOPATH的局部环境变量。 $GOPATH告诉编译器在哪里可以找到导入的第三方源代码以及您编写的任何本地源代码。 尽管不再明确要求使用它,但由于许多第三方工具仍依赖于此变量的设置,因此仍被认为是一种好的做法。

You can set your $GOPATH by adding the global variables to your ~/.profile. You may want to add this into .zshrc or .bashrc file as per your shell configuration.

您可以通过将全局变量添加到~/.profile来设置$GOPATH 。 您可能需要根据外壳程序配置将此文件添加到.zshrc.bashrc文件中。

First, open ~/.profile with nano or your preferred text editor:

首先,使用nano或您喜欢的文本编辑器打开~/.profile

  • nano ~/.profile

    纳米〜/ .profile

Set your $GOPATH by adding the following to the file:

通过将以下内容添加到文件中来设置$GOPATH

~/.profile
〜/ .profile
export GOPATH=$HOME/go

When Go compiles and installs tools, it will put them in the $GOPATH/bin directory. For convenience, it’s common to add the workspace’s /bin subdirectory to your PATH in your ~/.profile:

当Go编译并安装工具时,它将放置在$GOPATH/bin目录中。 为了方便起见,通常将工作区的/bin子目录添加到~/.profile PATH中:

~/.profile
〜/ .profile
export PATH=$PATH:$GOPATH/bin

This will allow you to run any programs you compile or download via the Go tools anywhere on your system.

这将允许您运行通过系统上任何位置的Go工具编译或下载的任何程序。

Finally, you need to add the go binary to your PATH. You can do this by adding /usr/local/go/bin to the end of the line:

最后,您需要将go二进制文件添加到PATH 。 您可以通过在行末添加/usr/local/go/bin来完成此操作:

~/.profile
〜/ .profile
export PATH=$PATH:$GOPATH/bin:/usr/local/go/bin

Adding /usr/local/go/bin to your $PATH makes all of the Go tools available anywhere on your system.

$PATH添加/usr/local/go/bin可使所有Go工具在系统上的任何位置可用。

To update your shell, issue the following command to load the global variables:

要更新您的shell,请发出以下命令以加载全局变量:

  • . ~/.profile

    。 〜/ .profile

You can verify your $PATH is updated by using the echo command and inspecting the output:

您可以通过使用echo命令并检查输出来验证$PATH是否已更新:

  • echo $PATH

    回声$ PATH

You will see your $GOPATH/bin which will show up in your home directory. If you are logged in as root, you would see /root/go/bin in the path.

您将看到$GOPATH/bin ,它将显示在主目录中。 如果您以root身份登录,则路径中将显示/root/go/bin


   
   
Output
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/root/go/bin:/usr/local/go/bin

You will also see the path to the Go tools for /usr/local/go/bin:

您还将看到/usr/local/go/bin的Go工具的路径:


   
   
Output
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/root/go/bin:/usr/local/go/bin

Verify the installation by checking the current version of Go:

通过检查Go的当前版本来验证安装:

  • go version

    去版本

And we should receive output like this:

我们应该收到这样的输出:


   
   
Output
go version go1.12.1 linux/amd64

Now that you have the root of the workspace created and your $GOPATH environment variable set, you can create your future projects with the following directory structure. This example assumes you are using github.com as your repository:

现在您已经创建了工作空间的根目录并设置了$GOPATH环境变量, $GOPATH可以使用以下目录结构创建将来的项目。 此示例假定您使用github.com作为存储库:

$GOPATH/src/github.com/username/project

So as an example, if you were working on the https://github.com/digitalocean/godo project, it would be stored in the following directory:

因此,举例来说,如果您正在使用https://github.com/digitalocean/godo项目,它将存储在以下目录中:

$GOPATH/src/github.com/digitalocean/godo

This project structure will make projects available with the go get tool. It will also help readability later. You can verify this by using the go get command and fetch the godo library:

该项目结构将使项目可通过go get工具使用。 这也将有助于以后的可读性。 您可以使用go get命令验证这一点并获取godo库:

  • go get github.com/digitalocean/godo

    去github.com/digitalocean/godo

This will download the contents of the godo library and create the $GOPATH/src/github.com/digitalocean/godo directory on your machine.

这将下载godo库的内容,并在您的计算机上创建$GOPATH/src/github.com/digitalocean/godo目录。

You can check to see if it successfully downloaded the godo package by listing the directory:

您可以通过列出以下目录来检查它是否成功下载了godo软件包:

  • ll $GOPATH/src/github.com/digitalocean/godo

    ll $ GOPATH / src / github.com / digitalocean / godo

You should see output similar to this:

您应该看到类似于以下的输出:


   
   
Output
drwxr-xr-x 4 root root 4096 Apr 5 00:43 ./ drwxr-xr-x 3 root root 4096 Apr 5 00:43 ../ drwxr-xr-x 8 root root 4096 Apr 5 00:43 .git/ -rwxr-xr-x 1 root root 8 Apr 5 00:43 .gitignore* -rw-r--r-- 1 root root 61 Apr 5 00:43 .travis.yml -rw-r--r-- 1 root root 2808 Apr 5 00:43 CHANGELOG.md -rw-r--r-- 1 root root 1851 Apr 5 00:43 CONTRIBUTING.md . . . -rw-r--r-- 1 root root 4893 Apr 5 00:43 vpcs.go -rw-r--r-- 1 root root 4091 Apr 5 00:43 vpcs_test.go

In this step, you created a Go workspace and configured the necessary environment variables. In the next step you will test the workspace with some code.

在此步骤中,您创建了Go工作区并配置了必要的环境变量。 在下一步中,您将使用一些代码来测试工作区。

步骤3 —创建一个简单程序 (Step 3 — Creating a Simple Program)

Now that you have the Go workspace set up, create a “Hello, World!” program. This will make sure that the workspace is configured properly, and also gives you the opportunity to become more familiar with Go. Because we are creating a single Go source file, and not an actual project, we don’t need to be in our workspace to do this.

现在您已经设置了Go工作区,创建一个“ Hello,World!”。 程序。 这将确保正确配置工作空间,并且还使您有机会更加熟悉Go。 因为我们创建的是单个Go源文件,而不是实际的项目,所以我们不需要在工作区中执行此操作。

From your home directory, open up a command-line text editor, such as nano, and create a new file:

在主目录中,打开一个命令行文本编辑器,例如nano ,并创建一个新文件:

  • nano hello.go

    nano hello.go

Write your program in the new file:

在新文件中编写程序:

package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
}

This code will use the fmt package and call the Println function with Hello, World! as the argument. This will cause the phrase Hello, World! to print out to the terminal when the program is run.

该代码将使用fmt包,并使用Hello, World!调用Println函数Hello, World! 作为论点。 这将导致短语Hello, World! 在程序运行时打印到终端。

Exit nano by pressing the CTRL and X keys. When prompted to save the file, press Y and then ENTER.

通过按CTRLX键退出nano 。 当提示您保存文件时,按Y ,然后按ENTER

Once you exit out of nano and return to your shell, run the program:

一旦退出nano并返回外壳,请运行程序:

go run hello.go

The hello.go program will cause the terminal to produce the following output:

hello.go程序将使终端产生以下输出:


   
   
Output
Hello, World!

In this step, you used a basic program to verify that your Go workspace is properly configured.

在此步骤中,您使用了一个基本程序来验证Go工作区是否已正确配置。

结论 (Conclusion)

Congratulations! At this point you have a Go programming workspace set up on your Ubuntu machine and can begin a coding project!

恭喜你! 至此,您已经在Ubuntu机器上设置了Go编程工作区,并且可以开始编码项目!

翻译自: https://www.digitalocean.com/community/tutorials/how-to-install-go-and-set-up-a-local-programming-environment-on-ubuntu-18-04

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值