安装
Ubuntu22 64 x86
golang
https://go.dev/doc/install
1.19
$ wget https://dl.google.com/go/go1.19.2.linux-amd64.tar.gz
# 删除旧版本go
$ rm -rf /usr/local/go
$ tar -C /usr/local -xzf go1.19.2.linux-amd64.tar.gz
配置环境变量
GOPATH
golangsrcsrcgithub.comsrc/github.com/user/project-ago get -u github.com/gin-gonic/ginpkgbin
创建工作空间如下
$ mkdir $HOME/golang
$ cd $HOME/golang
$ mkdir src pkg bin
$ cd src
$ mkdir -p github.com/gong/hello-world
GOROOT
golang
/etc/profile.d/golang.sh
export GOROOT=/usr/local/go
export PATH=$GOROOT/bin:$PATH
export GOPATH=$HOME/golang
shell
$ source /etc/profile
$ go version
go
$ go env -w GOPROXY=https://goproxy.cn,direct
Hello world
$HOME/golang/github.com/gong/hello-world
main.go
package main
import "fmt"
func main() {
fmt.Println("Hello World!")
}
编译之前需要执行一条命令,创建包的依赖文件,该文件记录了包的依赖信息
$ go mod init
更新依赖
$ go mod tidy
main.go
$ go build
$ ll
总用量 1.8M
-rw-rw-r-- 1 gong gong 44 10月 26 17:04 go.mod
-rwxrwxr-x 1 gong gong 1.8M 10月 26 17:04 hello-world
-rw-rw-r-- 1 gong gong 73 10月 26 16:59 main.go
hello-world
$ ./hello-world
Hello World!
或者可以直接编译运行一步到位
$ go run .
Hello World!
go web
gin
获取包
$ go get -u github.com/gin-gonic/gin
main.go
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "pong",
})
})
r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
执行命令更新依赖
$ go mod tidy
go.mod
web
$ go run .
http://127.0.0.1:8080/ping
docker
main.goDockerfile
由于是编译型语言,适合采用分阶段构建,达到最小镜像
FROM golang:1.19-alpine as builder
WORKDIR /work
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories \
&& go env -w GOPROXY=https://goproxy.cn,direct \
&& apk update \
&& apk add tzdata
ADD go.mod .
ADD go.sum .
RUN go mod download
COPY . .
RUN go build -o web
FROM alpine:3.16
WORKDIR /work
COPY --from=builder /work/web .
COPY --from=builder /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
RUN chmod +x web
ENTRYPOINT ["./web"]
web
$ docker build -t web .
查看镜像大小
$ docker images |grep web
web latest 259944109b18 About an hour ago 26.5MB
compose.yaml
gingin
services:
web:
image: web
container_name: web
ports:
- "8080:8080"
restart: always
environment:
- GIN_MODE=release
go.modgo.sumgo mod
$ ll
总用量 36K
-rw-rw-r-- 1 gong gong 148 10月 26 17:50 compose.yaml
-rw-rw-r-- 1 gong gong 468 10月 26 17:42 Dockerfile
-rw-rw-r-- 1 gong gong 2.9K 10月 26 17:38 go.mod
-rw-rw-r-- 1 gong gong 19K 10月 26 17:38 go.sum
-rw-rw-r-- 1 gong gong 280 10月 26 17:27 main.go
http://127.0.0.1:8080
$ docker compose up -d