83 lines
1.8 KiB
Go
83 lines
1.8 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"energy-management-system/core/cron"
|
|
"energy-management-system/core/gorm"
|
|
"energy-management-system/core/logger"
|
|
"energy-management-system/core/viper"
|
|
"energy-management-system/global"
|
|
"energy-management-system/request/validator"
|
|
"energy-management-system/router"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"time"
|
|
)
|
|
|
|
func init() {
|
|
// 配置
|
|
viper.InitViper()
|
|
// 日志
|
|
logger.InitLogger()
|
|
// 数据库
|
|
gorm.InitGorm()
|
|
// gin验证器
|
|
validator.InitTrans()
|
|
// 可选初始化表结构
|
|
gorm.AutoMigrate(global.Db)
|
|
// 可选初始化表数据
|
|
gorm.AutoInitDbData()
|
|
|
|
}
|
|
func main() {
|
|
|
|
cron.Register("0/1 * * * * ", func() {
|
|
fmt.Println(time.Now())
|
|
})
|
|
cron.CronRun()
|
|
|
|
r := router.InitRouter()
|
|
host := global.AppConf.Service.Http.Host
|
|
port := global.AppConf.Service.Http.Port
|
|
srv := initServer(host, port, r)
|
|
|
|
// 启动服务
|
|
go startServer(srv, host, port)
|
|
|
|
// 优雅关闭
|
|
gracefulShutdown(srv)
|
|
}
|
|
|
|
func initServer(host, port string, handler http.Handler) *http.Server {
|
|
return &http.Server{
|
|
Addr: fmt.Sprintf("%s:%s", host, port),
|
|
Handler: handler,
|
|
ReadTimeout: 60 * time.Second,
|
|
WriteTimeout: 60 * time.Second,
|
|
}
|
|
}
|
|
|
|
func startServer(srv *http.Server, host, port string) {
|
|
fmt.Println("Listening and serving HTTP on", host, ":", port)
|
|
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
fmt.Printf("listen: %s\n", err)
|
|
}
|
|
}
|
|
|
|
func gracefulShutdown(srv *http.Server) {
|
|
quit := make(chan os.Signal, 1)
|
|
signal.Notify(quit, os.Interrupt)
|
|
<-quit
|
|
fmt.Println("Shutdown Server ...")
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
if err := srv.Shutdown(ctx); err != nil {
|
|
fmt.Println("Server Shutdown:", err)
|
|
}
|
|
fmt.Println("Server exiting")
|
|
}
|