Gin安装、Hello程序编写和跨平台交叉编译

Gin安装、Hello程序编写和跨平台交叉编译
1. 设置国内镜像(可选)
编辑你的 shell 配置文件(例如.bash_profile,.zshrc等)
open -e ~/.zshrc # 如果你使用的是 zsh
加入国内镜像
export GOPROXY=https://goproxy.io,direct
其它镜像
七牛云:https://goproxy.cn,direct
腾讯云:https://mirrors.cloud.tencent.com/go/,direct
华为云:https://go.pkg.huaweicloud.com/,direct
阿里云:https://mirrors.aliyun.com/goproxy/,direct

2. 安装 Gin 框架
go get -u github.com/gin-gonic/gin
这个命令会:
下载 Gin 框架的最新版本
将依赖信息添加到 go.mod 文件
生成 go.sum 文件记录依赖的具体版本

3. 项目结构
my-gin-app/
├── config/             # 配置文件目录
│   ├── config.go      # 配置结构体定义
│   └── database.go    # 数据库配置
├── controllers/        # 控制器目录,处理请求和响应
│   ├── user.go        # 用户相关控制器
│   └── product.go     # 产品相关控制器
├── middleware/         # 中间件目录
│   ├── auth.go        # 认证中间件
│   └── logger.go      # 日志中间件
├── models/            # 数据模型目录
│   ├── user.go        # 用户模型
│   └── product.go     # 产品模型
├── routes/            # 路由配置目录
│   └── routes.go      # 路由定义
├── services/          # 业务逻辑目录
│   ├── user.go        # 用户相关业务逻辑
│   └── product.go     # 产品相关业务逻辑
├── utils/             # 工具函数目录
│   ├── jwt.go         # JWT 工具
│   └── validator.go   # 验证工具
├── main.go            # 应用程序入口
└── go.mod             # 依赖管理文件

4. 简单代码main.go
package main
import (
    "github.com/gin-gonic/gin"
    "net/http"
)
func main() {
    // 创建默认的 gin 引擎
    router := gin.Default()
    // 设置信任的代理
    router.SetTrustedProxies([]string{"127.0.0.1"})
    // 定义一个简单的路由
    router.GET("/", func(context *gin.Context) {
        context.JSON(http.StatusOK, gin.H{
            "message": "Hello, Gin!",
        })
    })
    // 启动服务器
    router.Run(":9527")
}

5. 编译Go程序为可执行文件
编译成本机可执行文件
go build main.go
交叉编译成Windows下的exe文件
GOOS=windows GOARCH=amd64 go build -o windows-bin.exe main.go
交叉编译生成Linux平台的可执行文件
GOOS=linux GOARCH=amd64 go build -o linux-bin main.go


3

相关文章