Taobin-Recipe-Manager/server/main.go

113 lines
2.1 KiB
Go
Raw Normal View History

2023-09-14 14:52:04 +07:00
package main
import (
"context"
2023-12-08 14:46:07 +07:00
"errors"
2023-09-14 14:52:04 +07:00
"log"
"os"
"os/signal"
2024-02-05 11:45:54 +07:00
"recipe-manager/config"
"recipe-manager/services/oauth"
2023-09-14 14:52:04 +07:00
"syscall"
"time"
2024-02-05 11:45:54 +07:00
"github.com/spf13/viper"
2023-09-14 14:52:04 +07:00
)
func main() {
2024-02-05 11:45:54 +07:00
config, err := loadConfig(".")
if err != nil {
// use default config instead
2024-02-05 11:45:54 +07:00
log.Fatal(err)
}
oauthService := oauth.NewOAuthService(config)
server := NewServer(config, oauthService)
tusServer := NewTusServer(config, oauthService)
2023-09-14 14:52:04 +07:00
serverCtx, serverStopCtx := context.WithCancel(context.Background())
2024-02-05 11:45:54 +07:00
tusServerCtx, tusServerStopCtx := context.WithCancel(context.Background())
2023-09-14 14:52:04 +07:00
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
go func() {
<-sig
2023-09-20 10:42:14 +07:00
shutdownCtx, cancel := context.WithTimeout(serverCtx, 30*time.Second)
2024-02-05 11:45:54 +07:00
tusShutdownCtx, tusShutdownCancel := context.WithTimeout(tusServerCtx, 30*time.Second)
2023-09-14 14:52:04 +07:00
go func() {
<-shutdownCtx.Done()
2023-12-08 14:46:07 +07:00
if errors.Is(shutdownCtx.Err(), context.DeadlineExceeded) {
2023-09-14 14:52:04 +07:00
log.Println("Shutdown timeout, force exit")
2023-09-20 10:42:14 +07:00
cancel()
2023-09-14 14:52:04 +07:00
}
}()
2024-02-05 11:45:54 +07:00
go func() {
<-tusShutdownCtx.Done()
if errors.Is(tusShutdownCtx.Err(), context.DeadlineExceeded) {
log.Println("Tus server shutdown timeout, force exit")
tusShutdownCancel()
}
}()
err := server.Shutdown(shutdownCtx)
if err != nil {
log.Fatal(err)
}
err = tusServer.Shutdown(tusShutdownCtx)
2023-09-14 14:52:04 +07:00
if err != nil {
log.Fatal(err)
}
2024-02-05 11:45:54 +07:00
tusServerStopCtx()
2023-09-14 14:52:04 +07:00
serverStopCtx()
}()
2023-10-30 10:45:33 +07:00
// Spawn a goroutine to run git pull every 10 minutes
2023-11-16 11:03:26 +07:00
//go RunGitRecipeWorker() // ** Use crontab instead **
2023-10-30 10:45:33 +07:00
2024-02-05 11:45:54 +07:00
go func() {
err := tusServer.Run()
if err != nil {
log.Fatal(err)
}
}()
go func() {
err := server.Run()
if err != nil {
log.Fatal(err)
}
}()
<-tusServerCtx.Done()
<-serverCtx.Done()
}
func loadConfig(path string) (*config.ServerConfig, error) {
viper.AddConfigPath(path)
viper.SetConfigName("app")
viper.SetConfigType("env")
viper.AutomaticEnv()
var serverConfig config.ServerConfig
err := viper.ReadInConfig()
2023-09-14 14:52:04 +07:00
if err != nil {
2024-02-05 11:45:54 +07:00
return nil, err
2023-09-14 14:52:04 +07:00
}
2024-02-05 11:45:54 +07:00
err = viper.Unmarshal(&serverConfig)
if err != nil {
return nil, err
}
return &serverConfig, nil
2023-09-14 14:52:04 +07:00
}