Why learn to Go

  1. Performance superiority; Go is extremely fast, with performance similar to Java or C++. In use, Go is typically 30 times faster than Python;
  2. Excellent performance in serialization/deserialization, sorting and aggregation;
  3. Developers are more productive; A variety of assignments, data structures, Pointers, formatting, and built-in HTTP libraries provide developers with a quick start.
  4. Natural concurrency, Go’s concurrency approach is very easy to learn;
  5. Fast compilation speed;
  6. Enhance team language cohesion; Go is very simple and easy to learn. It provides the basics without the extra. The new concept introduced by Go is the defer declaration, along with built-in Goroutines and concurrency management for channels.
  7. Go has a stable ecosystem; Go has great tool support.
  8. GOFMT, enforce code formatting; Gofmt uses an official formal specification code to avoid unnecessary discussion;
  9. Go has first-class support for Protocol Buffers and gRPC, etc.

Foreign companies such as Google, AWS, Cloudflare, CoreOS, etc., as well as domestic companies such as Tencent, Zhihu, Bilibili, Qiniu, Ali, etc., have started to use Golang to develop their cloud computing products on a large scale. Following in the footsteps of the world’s giants shouldn’t go in the wrong direction, and Golang’s design philosophy is convincing enough.

Yunfeng blog once said such a sentence:

I found that I spent four years honing my ability to build systems in C, trying to find a specification that would make it easier to write software. Turns out it was just a copy of Go. Lack of language level support, can only be a parody.

Environment set up

Download address

Go official website: golang.org/dl/

Go official image site (recommended) : golang.google.cn/dl/

The installation

Windows installation

Download the installation package selected in the previous step to the local PC.

Double-click the downloaded file and follow the instructions to install it.

Under Linux installation

If you do not need to type the go code on the Linux platform, there is no need to install go on the Linux platform. The Go code written on the developer only needs to be compiled cross-platform before it can be copied to run on the Linux server, which is also the advantage of easy cross-platform deployment of GO programs.

Wget HTTP: / / https://dl.google.com/go/go1.17.1.linux-amd64.tar.gzCopy the code

Unzip the downloaded file to /usr/local:

Tar -zxvf go1.17.1.linux-amd64.tar.gz -c /usr/local  # decompression
Copy the code

If no permission is displayed, add sudo as root and run again. After executing, you can see the go directory under /usr/local/.

Configure environment variables: In Linux, you can configure environment variables in two files. /etc/profile takes effect for all users. $HOME/. Profile is valid for the current user. Select a file to open according to your own situation, add the following two lines of code, save and exit.

export GOROOT=/usr/local/go
export PATH=$PATH:$GOROOT/bin
Copy the code

Profile takes effect after you run the source command to load $HOME/. Profile after you modify $HOME/. Check:

~ go version
go version go1.17.1 linux/amd64
Copy the code

The Mac, the installation

Download the executable version and click Install Next. By default, go will be installed in /usr/local/go.

check

After the previous installation is complete, open the terminal window and run the go version command to view the go version.

Configuration GOPATH

GOPATH is an environment variable that indicates where your go project is stored (the working directory).

It is best to set only one GOPATH path and place all project code in the GOPATH SRC directory.

Note: After Go1.11, enable itgo modConfiguration is no longer mandatory after modeGOPATH.

Note: After Go1.11, enable itgo modConfiguration is no longer mandatory after modeGOPATH.

Note: After Go1.11, enable itgo modConfiguration is no longer mandatory after modeGOPATH.

The following sections of GOPATH and project directory are available prior to Go1.11. We currently recommend that you use the latest Go language version and open itgo modMode. Code files can be stored anywhere.

For Linux and Mac platforms, add your working directory to the environment variable in the same way as above. For Windows, please do your own Google

Prior to Go 1.8, the GOPATH environment variable was empty by default. Starting with Go 1.8, the Go development kit sets a default directory for GOPATH after installation, as shown in the table below.

Default values for GOPATH on different operating system platforms

platform GOPATH default values For example,
Windows %USERPROFILE%/go C:\Users\ user name \go
Unix $HOME/go /home/username /go

At the same time, add the bin directory under GOROOT and the bin directory under GOPATH to the environment variable.

After configuring the environment variables, restart the terminal that is already open on the computer. (for example, terminals in CMD, VS Code, and other editors).

Go Project Structure

Regardless of the programming language, good project organization is critical because it directly affects the complexity of the internal dependencies of the project and the flexibility of the project to provide services such as apis externally. It is best to set up a structure agreement early in the project, and even develop tools such as scaffolding to generate project templates so that developers can participate in the project as consistently as possible.

The directory structure of a project is often a facade, and the insider can basically tell if the developer is experienced or not. The Go website does not provide a standard template for a directory structure, but Golang-standards does provide one, as follows:

API ├ ├ ─ ─ ─ ─ assets ├ ─ ─ build │ ├ ─ ─ ci │ └ ─ ─ package ├ ─ ─ CMD │ └ ─ ─ * your_app * ├ ─ ─ configs ├ ─ ─ deployments ├ ─ ─ docs ├ ─ ─ Examples ├ ─ ─ githooks ├ ─ ─ init ├ ─ ─ internal │ ├ ─ ─ app │ │ └ ─ ─ * * │ your_app └ ─ ─ PKG │ └ ─ ─ * your_private_lib * ├ ─ ─ PKG │ └ ─ ─ * your_public_lib * ├ ─ ─ scripts ├ ─ ─ the test ├ ─ ─ third_party ├ ─ ─ the tools ├ ─ ─ vendor ├ ─ ─ web │ ├ ─ ─ app │ ├ ─ ─ the static │ └ ─ ─ Template ├ ─ ─ website ├ ─ ─. Gitignore ├ ─ ─ LICENSE. The md ├ ─ ─ a Makefile ├ ─ ─ the README. Md └ ─ ─ go. The modCopy the code

This is the basic layout of the Go application project. It is not an official standard defined by the core Go development team; However, it is a common layout pattern for both old and new projects in the Go ecosystem. Some of these models are more popular than others. It also has a number of small enhancements, as well as several support directories that are common to any large enough real-world application.

The project layout is generic and there is no attempt to impose a specific Go package structure.

/cmd

Backbone of this project.

The directory name for each application should match the name of the executable you want (for example, / CMD /myapp).

Don’t put too much code in this directory. If you think the code can be imported and used in other projects, it should be in the/PKG directory. If your code is not reusable, or you don’t want others to reuse it, put it in the /internal directory. You’ll be surprised what others will do, so be clear about your intentions!

There is usually a small main function that imports and calls code from the /internal and/PKG directories, but nothing else.

/internal

Private application and library code. This is where you don’t want someone else importing code into their application or library. Note that this layout pattern is performed by the Go compiler itself. See Go 1.4 Release Notes for more details. Note that you are not limited to the top-level internal directory. There can be multiple internal directories at any level of the project tree.

You can choose to add some additional structure to the internal package to separate shared and non-shared internal code. This is not required (especially for smaller projects), but it is good to have visual clues to the intended purpose of the package. Your actual application code can be placed in /internal/app (e.g. /internal/app/myapp), and the code shared by these applications can be placed in /internal/ PKG (e.g. /internal/ PKG /myprivlib).

/pkg

Library code that can be used by external applications (e.g. / PKG/myPubliclib). Other projects import these libraries and hope they work, so think twice before putting anything in here 🙂 Note that the internal directory is a better way to ensure that private packages cannot be imported, since it is enforced by Go. The/PKG directory is still a good way to explicitly indicate that the code in that directory is a good way for others to use safely. The I’ll Take PKG over Internal blog post by Travis Jeffery provides a good overview of PKG and internal directories and when it makes sense to use them.

This is also a way to group Go code into one location when the root directory contains a large number of non-GO components and directories, making it easier to run various Go tools

If you want to see which popular Go repositories use this project layout pattern, check out the/PKG directory. This is a common layout pattern, but not everyone accepts it, and some in the Go community don’t recommend it.

If your application project is really small and additional nesting doesn’t add much value (unless you really want it :-), don’t use it. When it gets big enough that your root directory can become cumbersome (especially if you have a lot of non-GO application components), think about it.

/vendor

Application dependencies (manage them manually or use your favorite dependency management tool, such as the new built-in Go Modules feature). The go mod vendor command will create the /vendor directory for you. Note that if you are not using Go 1.14, which is enabled by default, you may need to add the -mod=vendor flag in the Go build command.

If you are building a library, do not submit your application dependencies.

Note that since 1.13, Go has also enabled the module proxy feature. If the module broker feature is enabled, the vendor directory is not required at all.

Domestic module agent function is the default wall, seven niuyun has a special maintenance module agent.

Service application directory

/api

OpenAPI/Swagger specification, JSON schema file, protocol definition file.

For an example, see/API directory.

Web application directory

/web

Web application-specific components: static Web assets, server-side templates, and SPAs.

General Application Directory

/configs

Configuration file template or default configuration.

Place the Confd or Consul-template template file here.

/init

System Init (Systemd, Upstart, SYSV) and Process Manager/Supervisor (Runit, Supervisor) configurations.

/scripts

Scripts that perform various build, install, analyze, and other operations.

These scripts to keep the root level Makefile become small and simple (for example, https://github.com/hashicorp/terraform/blob/master/Makefile).

For an example, see the /scripts directory.

/build

Packaging and continuous integration.

Place cloud (AMI), container (Docker), operating system (deb, RPM, PKG) package configurations and scripts in the /build/package directory.

Place CI (Travis, Circle, Drone) configurations and scripts in the /build/ CI directory. Note that some CI tools, such as Travis CI, are very picky about the location of configuration files. Try placing the configuration files in the /build/ci directory, linking them to where the CI tool expects them (if possible).

/deployments

IaaS, PaaS, systems and containers orchestrate deployment configurations and templates (Docker-compose, Kubernetes/HELM, MesOS, Terraform, BOSH). Note that in some repositories (especially applications deployed using Kubernetes), this directory is called /deploy.

/test

Additional external test applications and test data. The /test directory can be constructed on demand at any time. For larger projects, it makes sense to have a data subdirectory. For example, you can use /test/data or /test/testdata (if you need to ignore the contents of the directory). Note that Go also ignores the word “. Or directories or files beginning with “_”, so you have more flexibility in how you name your test data directories.

For an example, see the /test directory.

Other directories

/docs

Design and user documentation (in addition to those generated by GODoc).

See the /docs directory for examples.

/tools

Support tools for this project. Note that these tools can import code from the/PKG and /internal directories.

See the /tools directory for examples.

/examples

Examples of applications and/or common libraries.

For examples, see the /examples directory.

/third_party

External accessibility tools, fork code, and other third-party tools (such as Swagger UI).

/githooks

Git hooks.

/assets

Other resources (images, logos, and so on) used with the repository.

/website

If you don’t use the Github page, place your project’s website data here.

For an example, see the /website directory.

Directories that should not be owned

/src

Some Go projects do have a SRC folder, but this usually happens when the developer has a Java background, where it is a common pattern. If you can, try not to adopt this Java pattern.

Do not confuse the project-level SRC directory with the SRC directory that Go uses for its workspace, as described in How to Write Go Code. The $GOPATH environment variable points to your (current) workspace (by default, it points to $HOME/ Go on non-Windows systems). This workspace includes the top-level/PKG, /bin, and/SRC directories. Your actual project is ultimately a subdirectory under the/SRC, therefore, if your project has/SRC directory, then the path will be like this: / some/path/to/workspace/SRC/your_project/SRC/your_code. Go. Note that in Go 1.11, you can place projects outside of GOPATH, but that doesn’t mean using this layout pattern is a good idea.

Go development editor

Good editors can improve the efficiency of development, and two of the most popular editors are recommended.

The first is the Visual Studio Code + Go extension, which can be developed very efficiently and can be downloaded from the official website code.visualStudio.com/.

The second is Goland, launched by JetBrains, a veteran IDE company. All plug-ins have been fully integrated, making it easier to use and more powerful, suitable for novice veterans. You can download and use it from the official website www.jetbrains.com/go/.

The first Go program

go mod

With the Go Module, you can create the first Go project — Hello — anywhere. Open terminal execution in this directory

goAfter mod init is successfully executed, one is generatedgoThe mod fileCopy the code

Create a main.go file in this directory:

package main  // Declare the main package, indicating that it is currently an executable program

import "fmt"  // Import the built-in FMT package

func main(a){  // The main function is the entry point for program execution
	fmt.Println("Hello World!")  // 在终端打印 Hello World!
}
Copy the code

go build

Go Build means to compile the source code into an executable.

Execute in hello directory:

go build
Copy the code

Or run the following command in another directory:

go build hello
Copy the code

The Go compiler will go to GOPATH’s SRC directory to find the Hello project you want to compile

The compiled executable file is saved in the current directory where the compiled command is executed. In Windows, the hello.exe executable file is found in the current directory.

You can also use the -o argument to specify the name of the compiled executable.

go build -o aaaaaaa.exe
Copy the code

go install

Go Install, which means to install, compiles the source code to get the executable, then moves the executable to GOPATH’s bin directory. Because our environment variable is configured with the bin directory under GOPATH, we can execute the executable directly anywhere.

Cross-platform compilation

By default, go build executables are the current operating system executable files. If you want to compile a Linux executable file under Windows, you only need to specify the target operating system platform and processor architecture:

SET CGO_ENABLED=0 // Disable CGO SET GOOS= Linux // Target platform is Linux SET GOARCH= AMD64 // Target processor architecture is AMD64Copy the code

Code that uses CGO does not support cross-platform compilation

Then execute the go build command and the result is an executable that runs on the Linux platform.

Compiling 64-bit executables for Linux and Windows for Mac:

CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build
Copy the code

Compiling 64-bit executables for Mac and Windows under Linux:

CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build
Copy the code

Compiling 64-bit executable programs for the Mac platform under Windows:

SET CGO_ENABLED=0
SET GOOS=darwin
SET GOARCH=amd64
go build
Copy the code