准备工作
- 服务端 CentOS7
- 软件 git,docker-ce,go , make
- 本地代码编辑工具 vscode 可选
安装Go 编译器
wget https://mirrors.ustc.edu.cn/golang/go1.16.3.linux-amd64.tar.gz
tar -zxvf go1.16.3.linux-amd64.tar.gz -C /usr/local/
cat > /etc/profile.d/go.sh << EOF
export GOROOT=/usr/local/go
export PATH=$PATH:$GOROOT/bin
EOF
source /etc/profile
初始化工作目录
mkdir GinProject
cd GinProject
go mod init GinProject
go env -w GOPROXY=https://goproxy.cn
go get github.com/gin-gonic/gin
本地测试
进入 GinProject 目录,创建一段引用Gin的代码 main.go 实现简单的 get post 请求接口
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
v1 := r.Group("/v1")
{
v1.POST("/post", func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
message := c.PostForm("message")
c.JSON(200, gin.H{"status": message })
})
v1.GET("/get", func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.JSON(http.StatusOK, gin.H{"message": "Welcome Test Go Gin Get API!"})
})
}
//定义默认路由
r.NoRoute(func(c *gin.Context) {
c.JSON(http.StatusNotFound, gin.H{
"status": 404,
"error": "404, page not exists!",
})
})
r.Run(":8000")
}
执行命令,go build main.go
完成代码编译后,执行 ./main
,回返回如下信息:
[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] POST /v1/post --> main.main.func1 (3 handlers)
[GIN-debug] GET /v1/get --> main.main.func2 (3 handlers)
[GIN-debug] Listening and serving HTTP on :8000
构建容器镜像
- 进入GinProject 目录,创建Dockerfile
# build stage
FROM alpine:3.14 as build-stage
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories
RUN apk --no-cache add go ca-certificates
RUN mkdir -p /go/src /go/bin && chmod -R 777 /go
ENV GOPATH /go
ENV PATH /go/bin:$PATH
RUN mkdir -pv /src && \
cd /src && \
go mod init src && \
go env -w GOPROXY=https://goproxy.cn && \
go get github.com/gin-gonic/gin
COPY main.go /src
RUN cd /src && go build main.go
# production stage
#FROM scratch
FROM alpine:3.14
WORKDIR /
COPY --from=build-stage /src/main /
RUN chmod 755 /main
EXPOSE 8000
CMD ["/main"]
- 进入GinProject 目录,创建Makefile
all: run
build:
docker build -t gin-go:latest .
run: build
docker rm gin-api -f
docker run -d -t -i --network host --name gin-api gin-go
test:
go build main.go
./main
- 进入GinProject 目录,创建.gitignore
go.mod
go.sum
main
- 进入GinProject 目录, 创建
- 执行命令 make 构建镜像并运行,运行成功后,
- 验证功能
- 将验证过的代码提交,推送到远端Git仓库
git add Dockerfile Makefile main.go .gitignore
git commit -m "Init Gin Project" Dockerfile Makefile main.go .gitignore
git remote add origin git@github.com:xxxx/xxx.git
git push -u origin main