CentOS6.8 configure the GO Language Development Environment

Source: Internet
Author: User

CentOS6.8 configure the GO Language Development Environment
GuideThe Go language is the second open-source programming language released by Google 2009. The Go language is specially optimized for the programming of multi-processor system applications, programs compiled using Go can speed up to C or C ++ code, and are more secure and support parallel processes.In view of the fact that more open-source projects use Go as the development language, this article introduces how to build and use the GO development environment in Linux (CentOS 6.8.I. Go Installation and Use1. Download The Go source code package

https://storage.googleapis.com/golang/go1.6.3.linux-amd64.tar.gz

Upload to the/usr/local/src directory

2. Compile and install Go to/usr/local
tar zxvf go1.6.3.linux-amd64.tar.gz -C /usr/local/

# Note: you must use the root account or sudo to decompress the Go source code package.

3. Set the PATH environment variable and add/usr/local/go/bin to the environment variable.
export PATH=$PATH:/usr/local/go/bin
4. Install to a custom location

The Go binary file is installed in/usr/local/go by default, but the Go tool can be installed in different locations. You can define it by yourself. You only need to set the correct environment variables.

For example, to install Go in the HOME directory, you must add the environment variable to $ HOME/. profile.

export GOROOT=$HOME/goexport PATH=$PATH:$GOROOT/bin

Note: When installing Go to another directory, GOROOT must be set as an environment variable.

5. Check whether the installation program is correct.

By setting up a workspace and creating a simple program, check whether a simple program is correctly installed. Create a directory that contains your workspace, such as/data/work, and set the location pointed to by the GOPATH environment variable.

export GOPATH=/data/work

# If/data/work does not exist, create a new one

Then, create src/keystore in your work.

# cat hello.gopackage mainimport "fmt"func main {fmt.Printf("hello,world!\n")}

# Use go to compile hello. go

go install github.com/user/hello

# The above command refers to a program named hello (or hello.exe) put in your workspace. Execute the following command to get the output result.

$GOPATH/bin/hellohello,world!

# When hello, world! appears! It indicates that Go is successfully installed and can work.

2. Go workspace Introduction1. Organization Code Overview

A Go language program usually saves all the code in a work zone.

The workspace contains many version control libraries (managed by Git ).

Each repository contains one or more packages.

Each package consists of one or more source files in a directory.

The directory path of a package determines its import path.

Note: similar to other programming environments, each project has an independent workspace and the workspace is closely linked to the version control library.

2. workspace Introduction

A workspace is a directory hierarchy with three root directories:

Src contains the Go source file

Pkg contains objects and packages

Bin contains executable commands
Go tool creates source code packages and installs binary files to the pkg and bin directories.
The src directory usually contains multiple version control libraries (such as Git or Mercurial) to track the development of one or more source packages.
The following is an example of a good Workspace:

bin/hello # command executableoutyet # command executablepkg/linux_amd64/github.com/golang/example/stringutil.a # package objectsrc/github.com/golang/example/.git/ # Git repository metadatahello/hello.go # command sourceoutyet/main.go # command sourcemain_test.go # test sourcestringutil/reverse.go # package sourcereverse_test.go # test sourcegolang.org/x/image/.git/ # Git repository metadatabmp/reader.go # package sourcewriter.go # package source... (many more repositories and packages omitted) ...

The property diagram above shows a workspace that contains two repositories (example and image). The example repository contains two commands (hello, outyet ), the image library contains bmp packages and several other packages.

A typical workspace contains multiple source libraries that contain many software packages and commands. Most programmers store all source code and dependencies in a work zone.

3. GOPATH environment variable settings

The GOPATH environment variable specifies the location of the workspace. It is probably the only environment variable that needs to be set during code development.

Create a workspace directory and set the corresponding gopath. Your workspace can be located anywhere you like, but we will use/data/work in this document. Note that this cannot be the same path for your Go installation.

mkdir -p /data/workexport GOPATH=/data/work

For convenience. Add the bin of the workspace to PATH.

export PATH=$PATH:$GOPATH/bin
4. Import path

An import path is a string that uniquely identifies a package. The import path of a package corresponds to its location in the workspace or in a remote repository.

A short import path is provided from the software package of the standard library. For your own package, You must select a path that is not likely to conflict with the path to be added to the standard library or other external libraries in the future.

Note that you do not need to publish your code to a remote repository, you can create it. This is just a good habit to organize your code. If you publish it one day. In practice, you can select any path name, as long as it is a unique standard library and a larger de-ecosystem.

We will use github.com/useras our basic role. Create a directory in your workspace to keep the source code:

mkdir -p $GOPATH/src/github.com/user
5. First Project

Compile and run a simple program. First select a package path (we will use github.com/user/hello) and create the corresponding package directory in your workspace:

mkdir $GOPATH/src/github.com/user/hello

Create a file named hello. go. It was created above and skipped here.

cd $GOPATH/src/github.com/user/hellogo install$GOPATH/bin/hello

Or:

hello

If you are using a source code management system, it is now a good time to initialize a repository, add files, and submit your first changes. Again, this step is optional: you do not need to use source code management to write code.

cd $GOPATH/src/github.com/user/hellogit initInitialized empty Git repository in /data/work/src/github.com/user/hello/.git/git add hello.gogit commit -m "first commit"[master (root-commit) bbfb477] first commit
6. first library

Mkdir $ GOPATH/src/github.com/user/stringutil

Next, create a file named reverse. go under the directory with the following content:

// Package stringutil contains utility functions for working with strings.package stringutil// Reverse returns its argument string reversed rune-wise left to right.func Reverse(s string) string {r := []rune(s)for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {r[i], r[j] = r[j], r[i]}return string(r)}

Compile the test package using go build

$ go build github.com/user/stringutil

If the source code package directory is in the current location, you only need:

go build

The above operation does not generate an output file. You must use go install to output the package and object to the pkg directory of the job.

After the stringutil package is created, modify the original hello. go and use the stringutil package:

package mainimport ("fmt""github.com/user/stringutil")func main() {fmt.Printf(stringutil.Reverse("\n !oG ,olleH"))}

Whether using the go installation package or binary files, all related dependencies are automatically installed. So when you install the hello program:

$ go install github.com/user/hello

The corresponding stringutil package is automatically installed.

Run the new hello program and you can see that the message has been reversed.

# helloHello, Go!

After completing the preceding operations, the workspace should be:

├── bin│ └── hello # command executable├── pkg│ └── linux_amd64 # this will reflect your OS and architecture│ └── github.com│ └── user│ └── stringutil.a # package object└── src└── github.com└── user├── hello│ └── hello.go # command source└── stringutil└── reverse.go # package source

Note: go install puts the library file stringutil. a under pkg/linux_amd64 (the directory structure is the same as the source code structure ). In this way, the go command can directly find the corresponding package object to avoid unnecessary repeated compilation. Linux_amd64 is used for cross-compiling Based on the operating system and your system architecture.

All the Go executable programs are linked together in static mode. Therefore, related package objects (Libraries) are not required during runtime ).

7. Package commands

All Go source code starts with the following statement:

package name

The name is the default package reference name. All files in a package must use the same package name and the executable command must be main.

All package names in a binary file do not need to be unique, but the reference path must be unique.

8. Test

Go comes with a lightweight testing framework consisting of go test and testing packages.

You can create xx_test.go to write a test, which contains several TestXXX functions. The test framework will automatically execute these functions. If the function contains tError or t. Fail, the corresponding test will be judged as a failure.

Add a test file for stringutil $ GOPATH/src/github.com/user/stringutil/reverse_test.go, containing the following content:

Package stringutilimport "testing" func TestReverse (t * testing. t) {cases: = [] struct {in, want string} {"Hello, world", "dlrow, olleH" },{ "Hello, world", ", olleH "},{" "," "},}for _, c: = range cases {got: = Reverse (c. in) if got! = C. want {t. Errorf ("Reverse (% q) = % q, want % q", c. in, got, c. want )}}}

# Test with go test

# go test github.com/user/stringutilok github.com/user/stringutil 0.002s

# Similarly, you can ignore the path in the package folder and directly execute go test

[root@zabbix stringutil]# go testPASSok github.com/user/stringutil 0.002s
9. Remote package

The Reference Path of the package describes how to obtain the source code of the package through the version control system. The go tool automatically obtains the package file from the remote code repository through the reference path. For example, the examples used in this article are stored in github.com/golang/example. Go can directly obtain, generate, and install the corresponding package through the url of the package code repository.

[root@zabbix ~]# go get github.com/golang/example/hello[root@zabbix ~]# $GOPATH/bin/helloHello, Go examples!

If no corresponding package exists in the workspace, go places the corresponding package in the workspace specified by the GOPATH environment variable. (If the package already exists, go skips the code and runs go install directly)

After the preceding go get command is executed, the following result is displayed in the workspace Folder:

The hello command on github depends on the stringutil library in the same repository. hello. go imports data using the same path. Therefore, the go get command can directly find and install the corresponding dependent package.

import "github.com/golang/example/stringutil"

# It is best to share the Go package in this way.

# Note: For more information about the go tool remote package, refer to: https://golang.org/cmd/go/#hdr-Remote_import_paths

10. Official Address

Go efficient programming: https://golang.org/doc/effective_go.html

Example of Go programming: https://tour.golang.org/welcome/

Address: http://www.linuxprobe.com/set-go-env.html


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.