woj-server/internal/app/app.go

68 lines
1.4 KiB
Go
Raw Normal View History

2022-09-07 23:34:37 +08:00
package app
import (
"context"
"fmt"
2022-10-13 16:32:44 +08:00
"github.com/WHUPRJ/woj-server/global"
2022-09-07 23:34:37 +08:00
"github.com/WHUPRJ/woj-server/internal/router"
2022-09-17 11:22:55 +08:00
"github.com/WHUPRJ/woj-server/internal/service/jwt"
2022-10-13 16:32:44 +08:00
"github.com/WHUPRJ/woj-server/repo/postgresql"
"github.com/WHUPRJ/woj-server/repo/redis"
2022-09-07 23:34:37 +08:00
"go.uber.org/zap"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func Run(g *global.Global) error {
2022-09-08 22:00:25 +08:00
// Setup Database
g.Db = new(postgresql.Repo)
2022-09-08 22:00:25 +08:00
g.Db.Setup(g)
2022-09-07 23:34:37 +08:00
// Setup Redis
g.Redis = new(redis.Repo)
g.Redis.Setup(g)
2022-09-17 11:22:55 +08:00
// Setup JWT
g.Jwt = jwt.NewJwtService(g)
2022-09-08 22:00:25 +08:00
// Prepare Router
handler := router.InitRouters(g)
2022-09-07 23:34:37 +08:00
2022-09-08 22:00:25 +08:00
// Create Server
addr := fmt.Sprintf("%s:%d", g.Conf.WebServer.Address, g.Conf.WebServer.Port)
2022-09-07 23:34:37 +08:00
server := &http.Server{
Addr: addr,
2022-09-08 22:00:25 +08:00
Handler: handler,
2022-09-07 23:34:37 +08:00
}
2022-09-08 22:00:25 +08:00
// Run Server
2022-09-07 23:34:37 +08:00
go func() {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
g.Log.Fatal("ListenAndServe Failed", zap.Error(err))
}
}()
// Handle SIGINT and SIGTERM.
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
g.Log.Info("Shutting down server ...")
2022-09-08 22:00:25 +08:00
// Graceful Shutdown
2022-09-07 23:34:37 +08:00
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err := server.Shutdown(ctx)
if err != nil {
2022-09-08 22:00:25 +08:00
g.Log.Warn("Server Shutdown Failed", zap.Error(err))
}
err = g.Db.Close()
if err != nil {
g.Log.Warn("Database Close Failed", zap.Error(err))
2022-09-07 23:34:37 +08:00
}
return err
}