安装与配置 #

一、Go环境搭建 #

1.1 安装Go #

macOS安装:

bash
# 使用Homebrew安装
brew install go

# 或下载官方安装包
# https://go.dev/dl/

Linux安装:

bash
# 下载并安装
wget https://go.dev/dl/go1.22.0.linux-amd64.tar.gz
sudo tar -C /usr/local -xzf go1.22.0.linux-amd64.tar.gz

# 配置环境变量
echo 'export PATH=$PATH:/usr/local/go/bin' >> ~/.bashrc
source ~/.bashrc

Windows安装:

powershell
# 使用Chocolatey安装
choco install golang

# 或下载官方安装包
# https://go.dev/dl/

1.2 验证安装 #

bash
# 查看Go版本
go version
# 输出: go version go1.22.0 darwin/amd64

# 查看Go环境
go env

1.3 配置Go环境变量 #

bash
# 设置Go模块代理(国内推荐)
go env -w GOPROXY=https://goproxy.cn,direct

# 设置Go模块模式
go env -w GO111MODULE=on

# 查看配置
go env GOPROXY
go env GO111MODULE

1.4 常用环境变量 #

变量 说明 默认值
GOROOT Go安装目录 自动设置
GOPATH Go工作空间 $HOME/go
GOPROXY 模块代理 https://proxy.golang.org
GO111MODULE 模块模式 on
GOCACHE 构建缓存 自动设置

二、Gin安装 #

2.1 创建项目目录 #

bash
# 创建项目目录
mkdir gin-demo
cd gin-demo

# 初始化Go模块
go mod init gin-demo

2.2 安装Gin #

bash
# 安装Gin框架
go get -u github.com/gin-gonic/gin

# 查看依赖
go mod tidy

2.3 验证安装 #

创建 main.go 文件:

go
package main

import "github.com/gin-gonic/gin"

func main() {
    r := gin.Default()
    r.GET("/ping", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "pong",
        })
    })
    r.Run()
}

运行项目:

bash
go run main.go

访问 http://localhost:8080/ping 验证。

2.4 go.mod文件说明 #

go
module gin-demo

go 1.22

require github.com/gin-gonic/gin v1.9.1

三、开发环境配置 #

3.1 VS Code配置 #

安装Go扩展:

  1. 打开VS Code
  2. 安装 Go 扩展(Google官方)
  3. 安装Go工具:Cmd+Shift+PGo: Install/Update Tools

settings.json配置:

json
{
    "go.useLanguageServer": true,
    "go.lintTool": "golangci-lint",
    "go.lintOnSave": "package",
    "go.formatTool": "goimports",
    "editor.formatOnSave": true
}

3.2 GoLand配置 #

  1. 打开GoLand
  2. 配置GOROOT:Settings → Go → GOROOT
  3. 配置GOPATH:Settings → Go → GOPATH
  4. 启用Go Modules:Settings → Go → Go Modules

3.3 常用开发工具 #

工具 说明 安装命令
golangci-lint 代码检查 brew install golangci-lint
goimports 导入管理 go install golang.org/x/tools/cmd/goimports@latest
air 热重载 go install github.com/cosmtrek/air@latest
swag API文档生成 go install github.com/swaggo/swag/cmd/swag@latest

四、项目结构规范 #

4.1 基础项目结构 #

text
gin-demo/
├── main.go           # 程序入口
├── go.mod            # 模块定义
├── go.sum            # 依赖校验
├── config/           # 配置文件
│   └── config.go
├── handlers/         # 处理函数
│   └── user.go
├── middleware/       # 中间件
│   └── auth.go
├── models/           # 数据模型
│   └── user.go
├── routes/           # 路由定义
│   └── routes.go
└── utils/            # 工具函数
    └── response.go

4.2 分层项目结构 #

text
gin-demo/
├── cmd/              # 命令行工具
│   └── api/
│       └── main.go
├── internal/         # 私有代码
│   ├── handlers/
│   ├── middleware/
│   ├── models/
│   └── services/
├── pkg/              # 公共代码
│   └── utils/
├── config/           # 配置文件
├── docs/             # 文档
├── scripts/          # 脚本
├── go.mod
└── go.sum

4.3 初始化项目 #

bash
# 创建目录结构
mkdir -p cmd/api internal/{handlers,middleware,models,services} pkg/utils config docs scripts

# 初始化模块
go mod init github.com/yourname/gin-demo

# 创建main.go
touch cmd/api/main.go

五、配置管理 #

5.1 使用环境变量 #

go
package config

import "os"

type Config struct {
    Port string
    Mode string
}

func Load() *Config {
    return &Config{
        Port: getEnv("PORT", "8080"),
        Mode: getEnv("GIN_MODE", "debug"),
    }
}

func getEnv(key, defaultValue string) string {
    if value := os.Getenv(key); value != "" {
        return value
    }
    return defaultValue
}

5.2 使用配置文件 #

config.yaml:

yaml
server:
  port: 8080
  mode: debug

database:
  host: localhost
  port: 3306
  name: gin_demo
  user: root
  password: root

config.go:

go
package config

import (
    "fmt"
    "github.com/spf13/viper"
)

type Config struct {
    Server   ServerConfig
    Database DatabaseConfig
}

type ServerConfig struct {
    Port int
    Mode string
}

type DatabaseConfig struct {
    Host     string
    Port     int
    Name     string
    User     string
    Password string
}

func Load() (*Config, error) {
    viper.SetConfigName("config")
    viper.SetConfigType("yaml")
    viper.AddConfigPath(".")
    viper.AddConfigPath("./config")
    
    if err := viper.ReadInConfig(); err != nil {
        return nil, err
    }
    
    var config Config
    if err := viper.Unmarshal(&config); err != nil {
        return nil, err
    }
    
    return &config, nil
}

func (c *DatabaseConfig) DSN() string {
    return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
        c.User, c.Password, c.Host, c.Port, c.Name)
}

5.3 使用viper库 #

bash
go get github.com/spf13/viper
go
package main

import (
    "fmt"
    "github.com/spf13/viper"
)

func main() {
    viper.SetConfigFile(".env")
    viper.AutomaticEnv()
    
    if err := viper.ReadInConfig(); err != nil {
        panic(err)
    }
    
    port := viper.GetString("PORT")
    fmt.Println("Port:", port)
}

六、热重载配置 #

6.1 安装Air #

bash
go install github.com/cosmtrek/air@latest

6.2 初始化Air配置 #

bash
air init

6.3 .air.toml配置 #

toml
root = "."
tmp_dir = "tmp"

[build]
  cmd = "go build -o ./tmp/main ."
  bin = "./tmp/main"
  full_bin = "./tmp/main"
  include_ext = ["go", "tpl", "tmpl", "html"]
  exclude_dir = ["assets", "tmp", "vendor"]
  delay = 1000

[log]
  time = false

[color]
  main = "magenta"
  watcher = "cyan"
  build = "yellow"
  runner = "green"

6.4 运行项目 #

bash
# 使用Air运行
air

# 或指定配置文件
air -c .air.toml

七、常用命令 #

7.1 Go命令 #

命令 说明
go mod init 初始化模块
go mod tidy 整理依赖
go get package 添加依赖
go get -u package 更新依赖
go run main.go 运行程序
go build 编译程序
go test ./... 运行测试
go fmt ./... 格式化代码

7.2 Gin运行模式 #

go
// 设置运行模式
gin.SetMode(gin.ReleaseMode)  // 生产模式
gin.SetMode(gin.DebugMode)    // 调试模式
gin.SetMode(gin.TestMode)     // 测试模式

// 或通过环境变量
// export GIN_MODE=release

八、总结 #

8.1 核心要点 #

要点 说明
Go环境 安装Go并配置环境变量
Gin安装 使用go get安装
项目结构 按功能分层组织
配置管理 使用viper管理配置
热重载 使用air提升开发效率

8.2 下一步 #

现在你已经搭建好了开发环境,接下来让我们创建 第一个应用,开始Gin之旅!

最后更新:2026-03-28