搭建Gin通用框架

Gin Web 开发脚手架技术文档

项目概述

本项目是一个基于 Gin 框架的 Go Web 开发脚手架模板,提供了完整的项目结构、配置管理、日志记录、MySQL 和 Redis 数据库连接等常用功能集成。

项目结构

gindemo/
├── gindemo.exe          # 编译后的可执行文件
├── go.mod               # Go 模块定义文件
├── main.go              # 应用程序入口点
├── conf/                # 配置文件目录
│   ├── config.yaml      # 主配置文件
│   └── dev.yaml         # 开发环境配置文件
├── dao/                 # 数据访问层
│   ├── mysql/           # MySQL 相关
│   │   └── mysql.go
│   └── redis/           # Redis 相关
│       └── redis.go
├── logger/              # 日志模块
│   └── logger.go
├── router/              # 路由层
│   └── route.go
└── setting/             # 配置管理└── setting.go

配置文件

name: "ginweb"
mode: "release"
port: 8080
version: "v.0.0.1"
start_time: "2025-09-01"
machine_id: 1log:level: "info"filename: "web_app.log"max_size: 200max_age: 30max_backups: 7mysql:host: 127.0.0.1port: 13306dbname: "ginweb"user: "root"password: "root"max_open_conns: 200max_idle_conns: 50redis:host: 127.0.0.1port: 6379password: ""db: 0pool_size: 100

核心模块详解

1. 应用程序入口 (main.go)

package mainimport ("fmt""gindemo/dao/mysql""gindemo/dao/redis""gindemo/logger""gindemo/router""gindemo/setting""os"
)// Go Web 开发通用的脚手架模板
func main() {if len(os.Args) < 2 {fmt.Printf("need config file.eg: conf config.yaml")return}fmt.Println("load config file:", os.Args[1])// 加载配置if err := setting.Init(os.Args[1]); err != nil {fmt.Printf("load config failed, err:%v\n", err)return}//日志if err := logger.Init(setting.Conf.LogConfig, setting.Conf.Mode); err != nil {fmt.Printf("init logger failed, err:%v\n", err)return}// mysqlif err := mysql.Init(setting.Conf.MysqlConfig); err != nil {fmt.Printf("init mysql failed, err:%v\n", err)return}defer mysql.Close()// redisif err := redis.Init(setting.Conf.RedisConfig); err != nil {fmt.Printf("init redis failed, err:%v\n", err)return}defer redis.Close()//注册路由r := router.SetupRouter(setting.Conf.Mode)err := r.Run(fmt.Sprintf(":%d", setting.Conf.Port))if err != nil {fmt.Printf("start server failed, err:%v\n", err)return}
}

功能特点:

  • 命令行参数验证,要求指定配置文件路径
  • 模块化初始化流程:配置 → 日志 → MySQL → Redis → 路由
  • 完善的错误处理和资源清理(defer 关闭数据库连接)

2. 配置管理模块 (setting.go)

package settingimport ("fmt""github.com/fsnotify/fsnotify""github.com/spf13/viper"
)type AppConfig struct {Name      string `mapstructure:"name,omitempty"`Mode      string `mapstructure:"mode,omitempty"`Version   string `mapstructure:"version,omitempty"`StartTime string `mapstructure:"start_time,omitempty"`machineId string `mapstructure:"machine_id,omitempty"`Port      int    `mapstructure:"port,omitempty"`*LogConfig   `mapstructure:"log,omitempty"`*MysqlConfig `mapstructure:"mysql,omitempty"`*RedisConfig `mapstructure:"redis,omitempty"`
}type LogConfig struct {Level      string `mapstructure:"level,omitempty"`Filename   string `mapstructure:"filename,omitempty"`MaxSize    int    `mapstructure:"max_size,omitempty"`MaxAge     int    `mapstructure:"max_age,omitempty"`MaxBackups int    `mapstructure:"max_backups,omitempty"`
}
type MysqlConfig struct {Host         string `mapstructure:"host,omitempty"`Port         int    `mapstructure:"port,omitempty"`DB           string `mapstructure:"dbname,omitempty"`User         string `mapstructure:"user,omitempty"`Password     string `mapstructure:"password,omitempty"`MaxOpenConns int    `mapstructure:"max_open_conns,omitempty"`MaxIdleConns int    `mapstructure:"max_idle_conns,omitempty"`
}type RedisConfig struct {Host         string `mapstructure:"host,omitempty"`Port         int    `mapstructure:"port,omitempty"`Password     string `mapstructure:"password,omitempty"`DB           int    `mapstructure:"db,omitempty"`PoolSize     int    `mapstructure:"pool_size,omitempty"`MinIdleConns int    `mapstructure:"min_idle_conns,omitempty"`
}var Conf = new(AppConfig)func Init(filePath string) (err error) {viper.SetConfigFile(filePath)//读取配置信息err = viper.ReadInConfig()if err != nil {fmt.Printf("viper.ReadInConfig() failed, err:%v\n", err)return}//把读取到的配置信息反序列化到 Conf 变量中if err := viper.Unmarshal(Conf); err != nil {fmt.Printf("viper.Unmarshal() failed, err:%v\n", err)}viper.WatchConfig()viper.OnConfigChange(func(e fsnotify.Event) {fmt.Printf("Config file changed, filename:%s\n", e.Name)if err2 := viper.Unmarshal(Conf); err2 != nil {fmt.Printf("viper.Unmarshal() failed, err:%v\n", err2)}})return
}

功能特点:

  • 使用 viper 库实现 YAML 配置文件的读取和解析
  • 支持配置热加载,文件变更时自动重新加载配置
  • 结构化的配置定义,类型安全

3. 日志模块 (logger.go)

package loggerimport ("gindemo/setting""net""net/http""net/http/httputil""os""runtime/debug""strings""time""github.com/gin-gonic/gin""go.uber.org/zap""go.uber.org/zap/zapcore""gopkg.in/natefinch/lumberjack.v2"
)var lg *zap.Logger// Init 初始化lg
func Init(cfg *setting.LogConfig, mode string) (err error) {writeSyncer := getLogWriter(cfg.Filename, cfg.MaxSize, cfg.MaxBackups, cfg.MaxAge)encoder := getEncoder()var l = new(zapcore.Level)err = l.UnmarshalText([]byte(cfg.Level))if err != nil {return}var core zapcore.Coreif mode == "dev" {// 进入开发模式,日志输出到终端consoleEncoder := zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig())core = zapcore.NewTee(zapcore.NewCore(encoder, writeSyncer, l),zapcore.NewCore(consoleEncoder, zapcore.Lock(os.Stdout), zapcore.DebugLevel),)} else {core = zapcore.NewCore(encoder, writeSyncer, l)}lg = zap.New(core, zap.AddCaller())zap.ReplaceGlobals(lg)zap.L().Info("init logger success")return
}func getEncoder() zapcore.Encoder {encoderConfig := zap.NewProductionEncoderConfig()encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoderencoderConfig.TimeKey = "time"encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoderencoderConfig.EncodeDuration = zapcore.SecondsDurationEncoderencoderConfig.EncodeCaller = zapcore.ShortCallerEncoderreturn zapcore.NewJSONEncoder(encoderConfig)
}func getLogWriter(filename string, maxSize, maxBackup, maxAge int) zapcore.WriteSyncer {lumberJackLogger := &lumberjack.Logger{Filename:   filename,MaxSize:    maxSize,MaxBackups: maxBackup,MaxAge:     maxAge,}return zapcore.AddSync(lumberJackLogger)
}// GinLogger 接收gin框架默认的日志
func GinLogger() gin.HandlerFunc {return func(c *gin.Context) {start := time.Now()path := c.Request.URL.Pathquery := c.Request.URL.RawQueryc.Next()cost := time.Since(start)lg.Info(path,zap.Int("status", c.Writer.Status()),zap.String("method", c.Request.Method),zap.String("path", path),zap.String("query", query),zap.String("ip", c.ClientIP()),zap.String("user-agent", c.Request.UserAgent()),zap.String("errors", c.Errors.ByType(gin.ErrorTypePrivate).String()),zap.Duration("cost", cost),)}
}// GinRecovery recover掉项目可能出现的panic,并使用zap记录相关日志
func GinRecovery(stack bool) gin.HandlerFunc {return func(c *gin.Context) {defer func() {if err := recover(); err != nil {// Check for a broken connection, as it is not really a// condition that warrants a panic stack trace.var brokenPipe boolif ne, ok := err.(*net.OpError); ok {if se, ok := ne.Err.(*os.SyscallError); ok {if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {brokenPipe = true}}}httpRequest, _ := httputil.DumpRequest(c.Request, false)if brokenPipe {lg.Error(c.Request.URL.Path,zap.Any("error", err),zap.String("request", string(httpRequest)),)// If the connection is dead, we can't write a status to it.c.Error(err.(error)) // nolint: errcheckc.Abort()return}if stack {lg.Error("[Recovery from panic]",zap.Any("error", err),zap.String("request", string(httpRequest)),zap.String("stack", string(debug.Stack())),)} else {lg.Error("[Recovery from panic]",zap.Any("error", err),zap.String("request", string(httpRequest)),)}c.AbortWithStatus(http.StatusInternalServerError)}}()c.Next()}
}

功能特点:

  • 基于 zap 高性能日志库
  • 支持日志轮转(lumberjack)
  • 开发模式同时输出到文件和控制台
  • 提供 Gin 框架的日志中间件和异常恢复处理
  • 智能处理 broken pipe 等连接异常

4. MySQL 数据访问模块 (mysql.go)

package mysqlimport ("fmt""gindemo/setting"_ "github.com/go-sql-driver/mysql""github.com/jmoiron/sqlx"
)var db *sqlx.DBfunc Init(cfg *setting.MysqlConfig) (err error) {dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?parseTime=true&loc=Local", cfg.User, cfg.Password, cfg.Host, cfg.Port, cfg.DB)db, err = sqlx.Connect("mysql", dsn)if err != nil {return}db.SetMaxIdleConns(cfg.MaxIdleConns)db.SetMaxOpenConns(cfg.MaxOpenConns)return
}func Close() {_ = db.Close()
}

功能特点:

  • 使用 sqlx 增强的 MySQL 驱动
  • 支持连接池配置
  • 自动处理时区问题(loc=Local)

5. Redis 数据访问模块 (redis.go)

package redisimport ("fmt""gindemo/setting""github.com/go-redis/redis"
)var (client *redis.ClientNil    = redis.Nil
)func Init(cfg *setting.RedisConfig) (err error) {client = redis.NewClient(&redis.Options{Addr:         fmt.Sprintf("%s:%d", cfg.Host, cfg.Port),Password:     cfg.Password,DB:           cfg.DB,PoolSize:     cfg.PoolSize,MinIdleConns: cfg.MinIdleConns,})_, err = client.Ping().Result()if err != nil {return err}return nil
}func Close() {_ = client.Close()
}

功能特点:

  • 使用 go-redis 客户端库
  • 支持连接池配置
  • 导出 Nil 错误常量便于处理键不存在的情况

6. 路由管理模块 (route.go)

package routerimport ("gindemo/logger""net/http""github.com/gin-gonic/gin"
)func SetupRouter(mode string) *gin.Engine {if mode == gin.ReleaseMode {// gin 设置成发布模式gin.SetMode(gin.ReleaseMode)}router := gin.New()router.Use(logger.GinLogger(), logger.GinRecovery(true))router.GET("/ping", func(c *gin.Context) {c.String(http.StatusOK, "pong")})return router
}

功能特点:

  • 根据运行模式自动设置 Gin 模式
  • 集成 zap 日志中间件和异常恢复
  • 提供健康检查端点 /ping

启动和运行

编译项目

go build -o gindemo.exe main.go

运行项目

./gindemo.exe conf/config.yaml

测试服务

curl http://localhost:8080/ping

配置说明

应用配置

  • name: 应用名称
  • mode: 运行模式(debug/release/test)
  • port: HTTP 服务监听端口
  • version: 应用版本号
  • start_time: 启动时间标识
  • machine_id: 机器标识,用于分布式部署

日志配置

  • level: 日志级别(debug/info/warn/error)
  • filename: 日志文件名
  • max_size: 单个日志文件最大大小(MB)
  • max_age: 日志保留天数
  • max_backups: 最大备份文件数

MySQL 配置

  • 连接参数:主机、端口、数据库名、用户名、密码
  • 连接池:最大打开连接数、最大空闲连接数

Redis 配置

  • 连接参数:主机、端口、密码、数据库编号
  • 连接池:连接池大小、最小空闲连接数

扩展开发指南

添加新的配置项

  1. setting.go 的对应配置结构体中添加字段
  2. 在配置文件中添加相应的配置项
  3. 在需要使用的地方通过 setting.Conf 访问

添加新的路由

router.goSetupRouter 函数中添加新的路由定义:

router.GET("/new-endpoint", func(c *gin.Context) {// 处理逻辑
})

添加业务模块

  1. 创建新的包目录
  2. 实现相关功能
  3. main.go 中初始化和集成

总结

这个 Gin Web 开发脚手架提供了一个结构清晰、功能完整的起点,具有以下特点:

  1. 模块化设计:各功能模块职责清晰,便于维护和扩展
  2. 配置驱动:所有可变参数都通过配置文件管理
  3. 生产就绪:包含日志、监控、异常处理等生产环境必需功能
  4. 高性能:基于 Gin 和 zap 等高性能库
  5. 易于扩展:清晰的架构便于添加新功能

该项目适合作为中小型 Web 服务的开发基础,可根据具体需求进行进一步定制和扩展。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/diannao/100484.shtml
繁体地址,请注明出处:http://hk.pswp.cn/diannao/100484.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

windows 平台下 ffmpeg 硬件编解码环境查看

环境&#xff1a; 1&#xff0c;nvidia 显卡 2&#xff0c;驱动安装 powershell 下 执行如下命令&#xff0c;出现GPU信息 说明驱动安装正常。 nvidia-smi 3&#xff0c;安装支持 NVENC 的 FFmpeg &#xff08;1&#xff09;Windows 下 编译 FFmpeg 需要 CUDA Toolkit &am…

08_多层感知机

1. 单层感知机 1.1 感知机① 线性回归输出的是一个实数&#xff0c;感知机输出的是一个离散的类。1.2 训练感知机 ① 如果分类正确的话y<w,x>为正数&#xff0c;负号后变为一个负数&#xff0c;max后输出为0&#xff0c;则梯度不进行更新。 ② 如果分类错了&#xff0c;y…

安卓实现miniLzo压缩算法

LZO官方源码 http://www.oberhumer.com/opensource/lzo 找到miniLZO点击Dowload miniLZO下载源码 http://www.oberhumer.com/opensource/lzo/download/minilzo-2.10.tar.gz demo源码(包含安卓) https://github.com/xzw421771880/MiniLzo_Mobile.git 1.代码部分 1.1.测试…

如何在ubuntu下用pip安装aider,解决各种报错问题

aider中文文档网站上给出的安装说明比较简单&#xff1a; https://aider.doczh.com/docs/install.html 但是在一个干净的ubuntu环境中按文档中的命令安装时&#xff0c;会报错&#xff0c;经过一番尝试之后&#xff0c;解决了报错问题&#xff0c;成功完成了安装。 成功安装执…

Kotlin flow详解

流式数据处理基础 Kotlin Flow 是基于协程的流式数据处理 API&#xff0c;要深入理解 Flow&#xff0c;首先需要明确流的概念及其处理方式。 流(Stream)如同水流&#xff0c;是一种连续不断的数据序列&#xff0c;在编程中具有以下核心特征&#xff1a; 数据按顺序产生和消费支…

DeepSeek V3 深度解析:MoE、MLA 与 GRPO 的架构革新

简介 DeepSeek&#xff08;深度求索&#xff09;是一家源自中国的人工智能公司&#xff0c;成立于2023年&#xff0c;总部位于中国杭州。前身是国内量化投资巨头幻方量化的子公司。公司专注于开发低成本、高性能的AI模型&#xff0c;致力于通过技术创新推动人工智能技术的普惠…

Flask学习笔记(三)--URL构建与模板的使用

一、URL构建url_for()函数对于动态构建特定函数的URL非常有用。 该函数接受函数的名称作为第一个参数&#xff0c;并接受一个或多个关键字参数&#xff0c;每个参数对应于URL的变量部分。from flask import Flask, redirect, url_forapp Flask(__name__)app.route(/admin)def …

Pyside6 + QML - 从官方的例程开始

导言如上所示&#xff0c;登上Qt Pyside6的官方网址&#xff1a;https://doc.qt.io/qtforpython-6/index.html&#xff0c;点击“Write your first Qt application”的"Start here!"按钮。 效果&#xff1a;工程代码&#xff1a; github:https://github.com/q1641293…

Python爬虫实战:研究Pandas,构建物联网数据采集和分析系统

1. 引言 1.1 研究背景 物联网(Internet of Things, IoT)作为新一代信息技术的重要组成部分,已广泛应用于智能交通、环境监测、智慧家居等多个领域。据 Gartner 预测,到 2025 年全球物联网设备数量将达到 750 亿台,产生的数据量将突破 zettabyte 级别。物联网平台作为数据…

深度学习入门基石:线性回归与 Softmax 回归精讲

一、线性回归&#xff1a;从房价预测看懂 “连续值预测” 逻辑 线性回归是深度学习的 “敲门砖”&#xff0c;它的核心思想是用线性关系拟合数据规律&#xff0c;解决连续值预测问题—— 比如根据房屋特征估算房价、根据温度湿度预测降雨量等。 1. 从生活案例到数学模型 拿房价…

GPT-5-Codex CLI保姆级教程:获取API Key配置与openai codex安装详解

朋友们&#xff0c;就在 2025 年 9 月中旬&#xff0c;OpenAI 悄悄扔下了一颗重磅炸弹&#xff1a;GPT-5-Codex。 如果你以为这只是又一次平平无奇的模型升级&#xff0c;那可就大错特错了。 我可以这么说&#xff1a;软件开发的游戏规则&#xff0c;从这一刻起&#xff0c;可能…

基于Spark的用户实时分析

Spark的最简安装 1. 下载并解压 Spark 首先,我们需要下载 Spark 安装包。您可以选择以下方式之一: 方式一:从官网下载(推荐) # 在 hadoop01 节点上执行 cd /home/hadoop/app wget https://archive.apache.org/dist/spark/spark-2.3.1/spark-2.3.1-bin-hadoop2.7.tgz方…

OpenCV 风格迁移、DNN模块 案例解析及实现

图像风格迁移是计算机视觉领域极具趣味性的技术之一 —— 它能将普通照片&#xff08;内容图像&#xff09;与艺术画作&#xff08;风格图像&#xff09;的特征融合&#xff0c;生成兼具 “内容轮廓” 与 “艺术风格” 的新图像。OpenCV 的 DNN&#xff08;深度神经网络&#x…

MySQL 日志:undo log、redo log、binlog以及MVCC的介绍

一、MySQL 日志&#xff1a;undo log、redo log、binlogundo log&#xff08;回滚日志&#xff09;&#xff1a;是 Innodb 存储引擎层生成的日志&#xff0c;实现了事务中的原子性&#xff0c;主要用于事务回滚和 MVCC&#xff08;隔离性&#xff09;。 redo log&#xff08;重…

【面板数据】省及地级市农业新质生产力数据集(2002-2025年)

农业新质生产力是以科技创新为核心驱动力&#xff0c;以科技化、数字化、网络化和智能化为主线&#xff0c;通过技术革命性突破、生产要素创新性配置、产业深度转型升级&#xff0c;实现农业全要素生产率显著跃升的先进生产力形态 本数据基于2002-2025年各省政府工作报告中关于…

20250917在荣品RD-RK3588-MID开发板的Android13系统下使用tinyplay播放wav格式的音频

input keyevent 24 1|console:/sdcard # cat /proc/asound/cards console:/sdcard # ls -l /dev/snd/【需要打开Android13内置的音乐应用才会有声音出来&#xff0c;原因未知&#xff01;】 1|console:/sdcard # tinyplay /sdcard/Music/kiss8.wav -D 1 -d 020250917在荣品RD-R…

总共分为几种IP

IP&#xff08;Internet Protocol&#xff09;地址根据不同的分类标准可分为多种类型&#xff0c;以下是常见的分类方式&#xff1a;按版本分类IPv4&#xff1a;32位地址&#xff0c;格式为四组十进制数字&#xff08;如192.168.1.1&#xff09;&#xff0c;约43亿个地址&#…

【Linux】常用命令(六)

【Linux】常用命令&#xff08;六&#xff09;1. yum命令1.1 基本语法1.2 常用命令2. 从服务器把数据cp到本地3. uname命令3.1 常用命令1. yum命令 全称&#xff1a;Yellowdog Updater, Modified作用&#xff1a;是 RPM 包管理器的前端工具&#xff0c;用于基于 RPM 的 Linux …

go grpc开发使用

1、安装proto 下载 Windows 版本 打开官方发布页面 访问 Protocol Buffers 的 GitHub Releases 页面&#xff1a; &#x1f449; https://github.com/protocolbuffers/protobuf/releases 解压 ZIP 文件 将下载的 ZIP 文件解压到一个你容易找到的目录&#xff0c;例如&#xff1…

MyBatis分页:PageHelper

MyBatis分页&#xff1a;PageHelper &#x1f4d6; 前言&#xff1a;为什么需要分页&#xff1f; 在处理大量数据时&#xff0c;一次性从数据库查询并返回所有结果是不可行的&#xff0c;这会带来巨大的性能和内存开销。分页是解决这一问题的标准方案。而PageHelper是一个极其流…