wget https://dl.google.com/go/go1.12.4.linux-amd64.tar.gz sudo tar -zxvf go1.12.4.linux-amd64.tar.gz -C /opt
檢查安裝是否成功java
cd /opt/go/bin ./go version go version go1.12.4 linux/amd64
設置環境變量linux
vi /etc/profile
export GOROOT=/opt/go export GOPATH=/home/ubuntu/go export GOPROXY=https://goproxy.io export GOARCH=amd64 export GOOS=linux export GOTOOLS=$GOROOT/pkg/tool export PATH=$PATH:$GOROOT/bin:$GOPATH/bin source /etc/profile
其中,GOPROXY 能夠解決 golang.org/x/... 系列包沒法下載的問題。git
編寫 HelloWorld 文件,測試運行環境。github
package main import "fmt" func main(){ fmt.Println("hello,world!") }
go run hello.go go build hello.go
建立 go.mod 文件golang
go mod init hello
用 Gin 實現一個簡單的 http 服務json
import ( "gopkg.in/gin-gonic/gin.v1" "net/http" ) func main(){ router := gin.Default() router.GET("/", func(c *gin.Context) { c.String(http.StatusOK, "Hello World") }) router.Run(":8000") }
直接編譯執行 ubuntu
go run hello
能夠看到引用的包都被自動下載了瀏覽器
go: finding github.com/gin-contrib/sse latest go: finding github.com/gin-gonic/gin/render latest go: finding github.com/gin-gonic/gin/binding latest go: finding github.com/gin-gonic/gin/json latest go: finding golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223 go: downloading golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223 go: finding gopkg.in/go-playground/validator.v8 v8.18.2 go: finding github.com/ugorji/go/codec latest go: finding github.com/golang/protobuf/proto latest go: finding gopkg.in/yaml.v2 v2.2.2 go: downloading gopkg.in/go-playground/validator.v8 v8.18.2 go: downloading gopkg.in/yaml.v2 v2.2.2 go: finding github.com/ugorji/go v1.1.4 go: finding github.com/golang/protobuf v1.3.1 go: downloading github.com/ugorji/go v1.1.4 go: downloading github.com/golang/protobuf v1.3.1 go: extracting gopkg.in/go-playground/validator.v8 v8.18.2 go: extracting gopkg.in/yaml.v2 v2.2.2 go: extracting github.com/golang/protobuf v1.3.1 go: extracting github.com/ugorji/go v1.1.4 go: extracting golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223 go: finding gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405
HTTP 服務啓動正常,能夠經過瀏覽器訪問了。bash
[GIN-debug] [WARNING] Now Gin requires Go 1.6 or later and Go 1.7 will be required soon.
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production. - using env: export GIN_MODE=release - using code: gin.SetMode(gin.ReleaseMode) [GIN-debug] GET / --> main.main.func1 (3 handlers) [GIN-debug] Listening and serving HTTP on :8000