Go语言 基于gin定义一个简单的web server 开发框架(二)

1,405 阅读3分钟

路由

这个比较简单,就是注册路由的作用了

package route

import (
   "go_web_app/logger"
   "net/http"

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

func Setup() *gin.Engine {
   r := gin.New()
   // 最重要的就是这个日志库
   r.Use(logger.GinLogger(), logger.GinRecovery(true))
   r.GET("/", func(context *gin.Context) {
      context.String(http.StatusOK, "ok")
   })
   return r
}

启动流程

这个之前也介绍过,就是一个稍微复杂一点的优雅重启方案,

// 启动服务 (优雅关机)

srv := &http.Server{
   Addr:    fmt.Sprintf(":%d", viper.GetInt("app.port")),
   Handler: r,
}

go func() {
   // 开启一个goroutine启动服务
   if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
      zap.L().Error("listen: %s\n", zap.Error(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 {
   log.Fatal("Server Shutdown: ", err)
   zap.L().Error("Server Shutdown: ", zap.Error(err))
}
zap.L().Info("Server exiting")

优化代码-db 不要对外暴露

之前的代码里 把db 对外暴露 其实不合适,最好的方案还是 提供一个close 方法 这样对外暴露方法 不对外暴露db 是最合适的

// 初始化mysql
if err := mysql.Init(); err != nil {
   fmt.Printf("init mysql failed:%s \n", err)
   return
}
zap.L().Debug("mysql init success")
// 初始化redis
if err := redis.Init(); err != nil {
   fmt.Printf("init redis failed:%s \n", err)
   return
}

defer mysql.Close()
defer redis.Close()
var db *sqlx.DB

func Close() {
   _ = db.Close()
}

func Init() (err error) {
   dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True",
      viper.GetString("mysql.user"), viper.GetString("mysql.password"),
      viper.GetString("mysql.host"), viper.GetInt("mysql.port"),
      viper.GetString("mysql.dbname"),
   )
   // 也可以使用MustConnect连接不成功就panic
   db, err = sqlx.Connect("mysql", dsn)
   if err != nil {
      zap.L().Error("connect DB failed, err:%v\n", zap.Error(err))
      return
   }
   db.SetMaxOpenConns(viper.GetInt("mysql.max_open_connection"))
   db.SetMaxIdleConns(viper.GetInt("mysql.max_idle_connection"))
   return
}

优化配置项

前面的配置项 我们都是 通过字符串来取的,可读性不佳,我们现在要想办法 把config 转成一个结构体来处理,这样代码的可读性会更好

type AppConfig struct {
   Name         string `mapstructure:"name"`
   Mode         string `mapstructure:"mode"`
   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"`
   Port              int    `mapstructure:"port"`
   User              string `mapstructure:"user"`
   Password          string `mapstructure:"password"`
   DbName            string `mapstructure:"dbname"`
   MaxOpenConnection int    `mapstructure:"max_open_connection"`
   MaxIdleConnection int    `mapstructure:"max_idle_connection"`
}

type RedisConfig struct {
   Host     string `mapstructure:"host"`
   Password string `mapstructure:"passowrd"`
   Post     int    `mapstructure:"port"`
   Db       int    `mapstructure:"db"`
   PoolSize int    `mapstructure:"pool_size"`
}

然后改一下我们的viper读取的流程 其实主要就是序列化一下

var Config = new(AppConfig)

// Init 加载配置文件
func Init() error {
   viper.SetConfigName("config") // 配置文件的名称
   viper.SetConfigType("yaml")   // 配置文件的扩展名,这里除了json还可以有yaml等格式
   // 这个配置可以有多个,主要是告诉viper 去哪个地方找配置文件
   // 我们这里就是简单配置下 在当前工作目录下 找配置即可
   viper.AddConfigPath(".")
   err := viper.ReadInConfig()
   if err != nil {
      fmt.Println("viper init failed:", err)
      return err
   }
   // 变化就在这里 有个序列化对象的过程
   if err := viper.Unmarshal(Config); err != nil {
      fmt.Println("viper Unmarshal err", err)
   }
   viper.WatchConfig()
   viper.OnConfigChange(func(in fsnotify.Event) {
      fmt.Println("配置文件已修改")
   })
   return err
}

修改一下 mysql的init方法 这回传递一个mysql的config参数

func Init(config *setting.MysqlConfig) (err error) {
   dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True",
      config.User, config.Password,
      config.Host, config.Port,
      config.DbName,
   )
   // 也可以使用MustConnect连接不成功就panic
   db, err = sqlx.Connect("mysql", dsn)
   if err != nil {
      zap.L().Error("connect DB failed, err:%v\n", zap.Error(err))
      return
   }
   db.SetMaxOpenConns(viper.GetInt("mysql.max_open_connection"))
   db.SetMaxIdleConns(viper.GetInt("mysql.max_idle_connection"))
   return
}

使用的时候 只要这样即可

// 初始化mysql
if err := mysql.Init(setting.Config.MysqlConfig); err != nil {
   fmt.Printf("init mysql failed:%s \n", err)
   return
}

源码地址