go1.8 Installation and configuration steps

  • 2020-06-03 06:55:47
  • OfStack

Description:

I learned go language before (about version 0.9), but later it was updated too fast and not used much, so it was abandoned. This year, some projects need to be developed with go and picked up again.

This is what I have sorted out in the process of learning go language. It is recorded here for my reference in the future.

Operating system: CentOS 6.9_x64

go version: 1.8.3

Install go

Here directly install base 2, other ways please search by yourself.

1. Download and install go

The order is as follows:


wget https://storage.googleapis.com/golang/go1.8.3.linux-amd64.tar.gz --no-check-certificate
tar zxvf go1.8.3.linux-amd64.tar.gz
mv go /usr/local/

2. Add environment variables

vim /etc/profile

Add the following:


export PATH=$PATH:/usr/local/go/bin
export GOROOT=/usr/local/go

Make the configuration work:


[root@localhost ~]# source /etc/profile
[root@localhost ~]# go version
go version go1.8.3 linux/amd64
[root@localhost ~]#

Using go

Here's a simple example of how to compile and run go, but we won't discuss any more.

test1.go code:


package main

import "fmt"

func main() {
  fmt.Println("Email : Mike_Zhang@live.com")
}

General compilation run

1, through go build command to compile go source code into binary file;

2. Execute the compiled base 2 file.

Examples are as follows:


[root@localhost src]# go build test1.go
[root@localhost src]# ls
test1 test1.go
[root@localhost src]# ./test1
Email : Mike_Zhang@live.com
[root@localhost src]#

Run as a script

The go language lets you run programs directly from go run, and you can use this feature to run go programs as a script.

Method 1:


[root@localhost src]# go run test1.go
Email : Mike_Zhang@live.com
[root@localhost src]#

Method 2:

Add the following code in the header of the file:


//usr/bin/env go run $0 "$@"; exit

You can then grant executable permissions via chmod.

Examples are as follows:


[root@localhost src]# cat test1.go
//usr/bin/env go run $0 "$@"; exit

package main

import "fmt"

func main() {
    fmt.Println("Email : Mike_Zhang@live.com")
}

[root@localhost src]# chmod a+x test1.go
[root@localhost src]# ./test1.go
Email : Mike_Zhang@live.com
[root@localhost src]#

Well, that's all. I hope it helped.


Related articles: