This commit is contained in:
2025-11-11 20:47:43 +01:00
parent 17a671a417
commit 1dbfe08225
9 changed files with 322 additions and 57 deletions

View File

@@ -3,22 +3,30 @@ package app
import (
"context"
"fmt"
"go_oxspeak_server/config"
"go_oxspeak_server/network/http"
"go_oxspeak_server/network/udp"
"os"
"os/signal"
"syscall"
)
type App struct {
cfg *config.Config
// Serveurs
udpServer *udp.Server
httpServer *http.Server
// Context (to be used for graceful shutdown)
ctx context.Context
cancel context.CancelFunc
sigChan chan os.Signal
errChan chan error
}
func New() *App {
return &App{}
}
func (app *App) Run() error {
// Context pour gérer l'arrêt gracieux
func NewApp(cfg *config.Config) *App {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Channel pour capturer les signaux d'arrêt (Ctrl+c, etc...)
sigChan := make(chan os.Signal, 1)
@@ -27,29 +35,55 @@ func (app *App) Run() error {
// Channel pour les erreurs
errChan := make(chan error, 1)
// Servers
udpServer := udp.NewServer(cfg.Server.BindAddr)
httpServer := http.NewServer(cfg.Server.BindAddr)
return &App{
cfg: cfg,
udpServer: udpServer,
httpServer: httpServer,
ctx: ctx,
cancel: cancel,
sigChan: sigChan,
errChan: errChan,
}
}
func (app *App) Run() error {
// Context pour gérer l'arrêt gracieux
defer app.cancel()
// Lancer les app ici
go app.runWorker(ctx, errChan)
go app.runWorkers()
fmt.Println("App started, press CTRL+C to stop...")
select {
case err := <-errChan:
case err := <-app.errChan:
return fmt.Errorf("error in the app: %w", err)
case sig := <-sigChan:
case sig := <-app.sigChan:
fmt.Printf("\nSIGTERM received: %v, stopping app...\n", sig)
cancel() // Annule le context pour arrêter les goroutines
app.cancel() // Annule le context pour arrêter les goroutines
return nil
}
}
func (app *App) runWorker(ctx context.Context, err_chan chan<- error) {
for {
select {
case <-ctx.Done():
fmt.Println("Worker stopped")
return
default:
// Logique métier ...
func (app *App) runWorkers() {
// lancer le serveur udp
go func() {
if err := app.udpServer.Run(); err != nil {
app.errChan <- err
}
}
}()
// lancer le serveur http
go func() {
if err := app.httpServer.Run(); err != nil {
app.errChan <- err
}
}()
<-app.ctx.Done()
fmt.Println("App stopped")
}