alby-hub/cmd/http/main.go
Freepilot d9d7fe6195
[Freepilot] fix: startup error handling (#1413)
* fix: handle errors from service.NewService() in startup code

Previously, both HTTP and Wails startup code ignored errors from
service.NewService(ctx) using blank identifier (_), which could
cause panics later if NewService fails (e.g., unable to connect
to postgres database).

Now properly handle the error and exit gracefully with a fatal
log message when service initialization fails.

* fix: compile error

---------

Co-authored-by: Roland Bewick <roland.bewick@gmail.com>
2025-06-17 21:07:52 +07:00

69 lines
1.9 KiB
Go

package main
import (
"context"
"fmt"
nethttp "net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/getAlby/hub/http"
"github.com/getAlby/hub/logger"
"github.com/getAlby/hub/service"
"github.com/labstack/echo/v4"
log "github.com/sirupsen/logrus"
)
func main() {
log.Info("AlbyHub Starting in HTTP mode")
// Create a channel to receive OS signals.
osSignalChannel := make(chan os.Signal, 1)
// Notify the channel on os.Interrupt, syscall.SIGTERM. os.Kill cannot be caught.
signal.Notify(osSignalChannel, os.Interrupt, syscall.SIGTERM)
ctx, cancel := context.WithCancel(context.Background())
svc, err := service.NewService(ctx)
if err != nil {
log.WithError(err).Fatal("Failed to create service")
return
}
e := echo.New()
//register shared routes
httpSvc := http.NewHttpService(svc, svc.GetEventPublisher())
httpSvc.RegisterSharedRoutes(e)
//start Echo server
go func() {
if err := e.Start(fmt.Sprintf(":%v", svc.GetConfig().GetEnv().Port)); err != nil && err != nethttp.ErrServerClosed {
logger.Logger.WithError(err).Error("echo server failed to start")
cancel()
}
}()
var signal os.Signal
go func() {
// wait for exit signal
signal = <-osSignalChannel
logger.Logger.WithField("signal", signal).Info("Received OS signal")
cancel()
}()
//handle graceful shutdown
<-ctx.Done()
logger.Logger.WithField("signal", signal).Info("Context Done")
logger.Logger.Info("Shutting down echo server...")
ctx, cancel = context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err = e.Shutdown(ctx)
if err != nil {
logger.Logger.WithError(err).Error("Failed to shutdown echo server")
}
logger.Logger.Info("Echo server exited")
svc.Shutdown()
logger.Logger.Info("Service exited")
logger.Logger.Info("Alby Hub needs to stay online to send and receive transactions. Channels may be closed if your hub stays offline for an extended period of time.")
}