golang web项目脚手架搭建
1、CLD分层: a、controller层:控制层,服务的入口,负责处理路由,参数校验,请求转发。 b、logic层:业务逻辑层。通过了controller层到达这里的所有请求参数一定是合法的。业务逻辑和业务流程都在这一层。 c、dao层:主要负责与数据、存储。将下层存储以函数形式、接口形式暴露给logic层。
2、其他层 a、logger层:存放日志 b、model层:程序功能实现文件、以及数据库sql创建表语句等。 c、setting层:配置文件 d、routes层:路由层
初始化脚手架 1、main函数每次启动项目都要初始化配置、日志文件logger、mysql文件、redis、以及路由的启动
func main() {
if err := setting.Init();err != nil{
return
}
if err := logger.Init(setting.Conf.LogConfig); err!=nil{
return
}
defer zap.L().Sync()
if err := mysql.Init(setting.Conf.MySQLConfig); err != nil{
return
}
defer mysql.Close()
if err := redis.Init(setting.Conf.RedisConfig); err != nil{
return
}
defer redis.Close()
if err := snowflake.Init(setting.Conf.StartingTime,setting.Conf.MachineID);err!=nil{
}
r := routes.SetUp()
srv := &http.Server{
Addr: fmt.Sprintf(":%d", viper.GetInt("app.port")),
Handler: r,
}
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
zap.L().Info("shutdown")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
zap.L().Fatal("Server Shutdown: ", zap.Error(err))
}
zap.L().Info("Server exiting")
}
setting.go文件
package setting
import (
"fmt"
"github.com/spf13/viper"
"github.com/fsnotify/fsnotify"
)
var Conf = new(App)
type App struct{
}
func Init()(err error){
viper.AddConfigPath('./')
viper.SetConfigName('config')
viper.SetConfigType('yaml')
err = viper.ReadInConfig()
viper.WatchConfig()
viper.OnConfigChange(func(in fsnotify.Event)){
}
return
}
logger.go日志文件
package logger
import (
"github.com/natefinch/lumberjack"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/gin-gonic/gin"
)
func Init(cfg *settings.LogCofig) (err error){
writeSyncer := getLogWriter(
)
encoder := getEncoder()
var l = new(zapcore.Level)
err = l.UnmarshalText([]byte(cfg.Level))
core := zapcore.NewCore(encoder,writeSyncer,l)
lg := zap.New(core, zap.AddCaller())
zap.ReplaceGlobals(lg)
return
}
func getLogWirter(filename string, maxSize, maxBackup, maxAge int) zapcore.WriteSyncer {
lumberJackLogger := &lumberjack.Logger{
Filename: filename,
MaxSize: maxSize,
MaxBackups: maxBackups,
MaxAge: maxAge,
}
return zapcore.AddSync(luberJackLogger)
}
mysql.go
package mysql
import (
_ "github.com/go-mysql-driver/mysql"
"github.com/jmoiron/sqlx"
"go.uber.org/zap"
)
var db *sqlx.DB
func Init(cfg *settings.MySQLConfig) (err error){
dsn:= fmt.Sprintf("%s:%s@tcp(%s:%d)/%s",
cfg.User,
cfg.Password,
cfg.Host,
cfg.Port,
cfg.DbName,)
db, err = sqlx.Connect("mysql", dsn)
if err ...
}
redis.go
package redis
import (
"github.com/go-redis/redis"
)
func Init(cfg *setting.RedisConfig) (err error){
rdb = redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%d",cfg.Host,cfg.Port),
Password: fmt.Sprintf("%s",cfg.Password),
DB: cfg.DB,
PoolSize: cfg.poolsize,
})
_,err = rdb.Ping().Result()
return
}
|