Go web 开发
gin框架开发通用模板
- 为了方便以后的开发需要哈,今天搞一套比较实用的开发脚手架
- 其中包含了
配置文件
、日志
、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
}
日志记录模块
- 在go的领域里面,日志当然要用
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