配置文件
、日志
、mysql初始化
、redis初始化
、路由模块
、main函数整合
。实体类models
、控制层controllers
、逻辑层logic或者服务层service
。Viper
来进行管理!代码预览
package settings
// 利用我们的 viper ,来管理设置我们的配置文件
import (
"fmt"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
// Conf 全局变量,用来保存全局的配置信息
var Conf = new(AppConfig)
type AppConfig struct {
Name string `mapstructure:"name"`
Mode string `mapstructure:"mode"`
Version string `mapstructure:"version"`
Port int `mapstructure:"port"`
*LogConfig `mapstructure:"log"`
*MySQLConfig `mapstructure:"mysql"`
*RedisConfig `mapstructure:"redis"`
}
type LogConfig struct {
Level string `mapstructure:"level"`
Filename string `mapstructure:"filename"`
MaxSize int `mapstructure:"max_size"`
MaxAge int `mapstructure:"max_age"`
MaxBackups int `mapstructure:"max_backups"`
}
type MySQLConfig struct {
Host string `mapstructure:"host"`
User string `mapstructure:"user"`
Password string `mapstructure:"password"`
DbName string `mapstructure:"db_name"`
Port int `mapstructure:"port"`
MaxOpenConns int `mapstructure:"max_open_conns"`
MaxIdleConns int `mapstructure:"max_idle_conns"`
}
type RedisConfig struct {
Host string `mapstructure:"host"`
Password string `mapstructure:"password"`
Port int `mapstructure:"port"`
DB int `mapstructure:"db"`
PoolSize int `mapstructure:"pool_size"`
}
func Init()(err error) {
viper.SetConfigFile("settings/config.yaml")
//viper.SetConfigName("config")
//viper.SetConfigType("yaml") // 指定配置文件类型,专门用于从远程获取配置信息时指定配置文件的类型
viper.AddConfigPath("settings")
err = viper.ReadInConfig() // 读取配置文件
if err != nil {
// 读取配置文件失败
fmt.Println("viper.ReadInConfig() failed,err : ",err)
return
}
// 将配置文件的信息序反列化到结构体里面
if err := viper.Unmarshal(Conf); err != nil {
fmt.Printf("viper.Unmarshal failed, err:%v \n",err)
}
// 配置文件热加载
viper.WatchConfig()
viper.OnConfigChange(func(in fsnotify.Event) {
fmt.Println("配置文件发生修改......")
if err := viper.Unmarshal(Conf); err != nil {
fmt.Printf("viper.Unmarshal failed, err:%v \n",err)
}
})
return
}
Zap
啦,不知道的请看 Zap详解代码预览
package logger
import (
"github.com/gin-gonic/gin"
"github.com/natefinch/lumberjack"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"net"
"net/http"
"net/http/httputil"
"os"
"runtime/debug"
"strings"
"time"
"web_app2/settings"
)
// Init 初始化Logger
func Init(cfg *settings.LogConfig) (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
}
core := zapcore.NewCore(encoder, writeSyncer, l)
//fmt.Sprintf("%s",core)
lg := zap.New(core, zap.AddCaller()) // 保存到文件里面
//lg,_ := zap.NewDevelopment() // 打印到控制台,以空格的方式
//lg,_ := zap.NewProduction() // 打印到控制台,以json的方法
// 替换zap包中全局的logger实例,后续在其他包中只需使用zap.L()调用即可
zap.ReplaceGlobals(lg)
return
}
func getEncoder() zapcore.Encoder {
encoderConfig := zap.NewProductionEncoderConfig()
encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
encoderConfig.TimeKey = "time"
encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
encoderConfig.EncodeDuration = zapcore.SecondsDurationEncoder
encoderConfig.EncodeCaller = zapcore.ShortCallerEncoder
return zapcore.NewConsoleEncoder(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.Path
query := c.Request.URL.RawQuery
c.Next()
cost := time.Since(start)
zap.L().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 bool
if 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 {
zap.L().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: errcheck
c.Abort()
return
}
if stack {
zap.L().Error("[Recovery from panic]",
zap.Any("error", err),
zap.String("request", string(httpRequest)),
zap.String("stack", string(debug.Stack())),
)
} else {
zap.L().Error("[Recovery from panic]",
zap.Any("error", err),
zap.String("request", string(httpRequest)),
)
}
c.AbortWithStatus(http.StatusInternalServerError)
}
}()
c.Next()
}
}
代码预览
package mysql
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
"go.uber.org/zap"
"web_app2/settings"
)
var db *sqlx.DB
func Init(cfg *settings.MySQLConfig) (err error) {
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True",
cfg.User,
cfg.Password,
cfg.Host,
cfg.Port,
cfg.DbName,
)
// 也可以使用MustConnect连接不成功就panic
db, err = sqlx.Connect("mysql", dsn)
if err != nil {
zap.L().Error("connect DB failed ", zap.Error(err))
return
}
db.SetMaxOpenConns(cfg.MaxOpenConns)
db.SetMaxIdleConns(cfg.MaxIdleConns)
return
}
func Close() {
_ = db.Close()
}
代码预览
package redis
import (
"fmt"
"github.com/go-redis/redis"
"web_app2/settings"
)
// redis
// 定义一个全局变量
var redisdb *redis.Client
func Init(cfg *settings.RedisConfig)(err error){
redisdb = redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%d",cfg.Host,cfg.Port), // 指定
Password: cfg.Password,
DB:cfg.DB, // redis一共16个库,指定其中一个库即可
PoolSize: cfg.PoolSize,
})
_,err = redisdb.Ping().Result()
return
}
func Close() {
_ = redisdb.Close()
}
代码预览
package routes
import (
"github.com/gin-gonic/gin"
"net/http"
"web_app2/logger"
)
func Setup() ( *gin.Engine ) {
r := gin.New()
r.Use(logger.GinLogger(),logger.GinRecovery(true))
r.GET("/", func(c *gin.Context) {
c.String(http.StatusOK,"ok")
})
return r
}
代码预览
package main
import (
"context"
"fmt"
"github.com/spf13/viper"
"go.uber.org/zap"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"web_app2/dao/mysql"
"web_app2/dao/redis"
"web_app2/logger"
"web_app2/routes"
"web_app2/settings"
)
// Go Web开发比较通用的脚手架模板
func main() {
// 1. 加载配置
if err := settings.Init(); err!= nil {
fmt.Println("init Settings failed!!! err:",err)
return
}
// 2. 初始化日志
if err := logger.Init(settings.Conf.LogConfig); err != nil {
fmt.Println("init Logger failed!!! err : ",err)
return
}
defer zap.L().Sync() // 将缓存区的日志追加到磁盘文件当中
zap.L().Debug("logger init success.....")
// 3. 初始化SQL连接
if err := mysql.Init(settings.Conf.MySQLConfig); err != nil {
fmt.Println("init Mysql failed!!! err : ",err)
return
}
defer mysql.Close()
// 4. 初始化redis连接
if err := redis.Init(settings.Conf.RedisConfig); err != nil {
fmt.Println("init Redis failed!!! err",err)
return
}
defer redis.Close()
// 5. 注册路由
r := routes.Setup()
// 6.启动服务(优雅关机,重启)
srv := &http.Server{
Addr: fmt.Sprintf(":%d",settings.Conf.Port),
Handler: r,
}
go func() {
// 开启一个goroutine启动服务
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
// 等待中断信号来优雅地关闭服务器,为关闭服务器操作设置一个5秒的超时
quit := make(chan os.Signal, 1) // 创建一个接收信号的通道
// kill 默认会发送 syscall.SIGTERM 信号
// kill -2 发送 syscall.SIGINT 信号,我们常用的Ctrl+C就是触发系统SIGINT信号
// kill -9 发送 syscall.SIGKILL 信号,但是不能被捕获,所以不需要添加它
// signal.Notify把收到的 syscall.SIGINT或syscall.SIGTERM 信号转发给quit
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) // 此处不会阻塞
<-quit // 阻塞在此,当接收到上述两种信号时才会往下执行
zap.L().Info("Shutdown Server ...")
// 创建一个5秒超时的context
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// 5秒内优雅关闭服务(将未处理完的请求处理完再关闭服务),超过5秒就超时退出
if err := srv.Shutdown(ctx); err != nil {
zap.L().Fatal("Server Shutdown: ", zap.Error(err))
}
zap.L().Info("Server exiting")
}