安装golang

golang,本节目标为安装golang,并完成hello world

系统环境为win11,下载地址

安装后检查版本

PS C:\Users\pc> go.exe version
go version go1.19.3 windows/amd64

设置国内包加速器

C:\> $env:GO111MODULE = "on"
C:\> $env:GOPROXY = "https://goproxy.cn"

可选的goproxy:

七牛: https://goproxy.cn
阿里: mirrors.aliyun.com/goproxy/
官方: https://goproxy.io/
其他: https://gocenter.io

接下来开始hello word 示例

  1. 生成一个go.mod 用于追踪代码的版本和依赖包
PS C:\Users\pc\Desktop> go mod init example/hello
go: creating new go.mod: module example/hello
go: to add module requirements and sums:
        go mod tidy
  1. 编写代码
  • 第一个程序 hello world

    package main
    
    import "fmt"
    
    func main() {
    	fmt.Println("Hello, World!")
    }
    
  • 第二个程序调用第三方包

    package main
    
    import (
    	"fmt"
    
    	"rsc.io/quote"
    )
    
    func main() {
    	fmt.Println(quote.Go())
    }
    
  1. 运行
PS C:\Users\pc\Desktop> go run . 
Hello, World!
  1. 打包
go build hello.go
  1. 制作image
[root@localhost test]# cat Dockerfile 
FROM scratch

COPY ./hello /hello

CMD ["/hello"]
  1. 运行docker
docker build . -t helloworld
[root@localhost test]# docker run --rm helloworld 
Hello, World!

在linux中环境安装

# centos 启动桌面环境
yum groupinstall "X Window System"
yum groupinstall -y "GNOME Desktop"
init 5
安装golang
wget https://golang.google.cn/dl/go1.19.6.linux-amd64.tar.gz
tar xf go1.19.6.linux-amd64.tar.gz -C /opt/
export GOROOT=/opt/go
export GOPATH=/home/pc/golang
export PATH=$GOROOT/bin:$PATH
export GO111MODULE="on"
export GOPROXY="https://goproxy.cn"
mkdir /home/pc/golang
安装vscode
sudo rpm --import https://packages.microsoft.com/keys/microsoft.asc
sudo sh -c 'echo -e "[code]\nname=Visual Studio Code\nbaseurl=https://packages.microsoft.com/yumrepos/vscode\nenabled=1\ngpgcheck=1\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc" > /etc/yum.repos.d/vscode.repo'

yum check-update
sudo yum install code

参考:
阅读以下 Go 知名的免费教程:

第一本 《The Little Go Book》https://learnku.com/docs/the-little-go-book

短小精湛,涵盖 Go 的语言基础,一两个小时内即可阅读完毕,社区有 中文译本 。

第二本《The Way to Go》https://learnku.com/docs/the-way-to-go

备受好评的教程,深入浅出,基本上涵盖 Go 语言的方方面面。中文命名 《Go 入门指南》,前往阅读 ,与社区 Wiki 一样,不要求学会,但是适合在你学习的不同阶段重复学习的课程。

第三本《Go Web 编程》https://learnku.com/docs/build-web-application-with-golang

使用 Go 做 Web 编程相关的课程。前往阅读。

posted @ 2022-12-01 13:55  mingtian是吧  阅读(78)  评论(0编辑  收藏  举报