refactor: move HTTP server to its own constructor

This commit is contained in:
Derrick Hammer 2024-01-28 05:07:13 -05:00
parent e6c1bab602
commit 47422524b8
Signed by: pcfreak30
GPG Key ID: C997C339BE476FF2
2 changed files with 35 additions and 28 deletions

View File

@ -1,10 +1,15 @@
package main package main
import ( import (
"context"
"crypto/ed25519" "crypto/ed25519"
"git.lumeweb.com/LumeWeb/portal/api/registry"
"github.com/spf13/viper" "github.com/spf13/viper"
"go.sia.tech/core/wallet" "go.sia.tech/core/wallet"
"go.uber.org/fx"
"go.uber.org/zap" "go.uber.org/zap"
"net"
"net/http"
) )
func initCheckRequiredConfig(logger *zap.Logger, config *viper.Viper) error { func initCheckRequiredConfig(logger *zap.Logger, config *viper.Viper) error {
@ -53,3 +58,32 @@ func NewIdentity(config *viper.Viper, logger *zap.Logger) (ed25519.PrivateKey, e
return ed25519.PrivateKey(wallet.KeyFromSeed(&seed, 0)), nil return ed25519.PrivateKey(wallet.KeyFromSeed(&seed, 0)), nil
} }
func NewServer(lc fx.Lifecycle, config *viper.Viper, logger *zap.Logger) (*http.Server, error) {
srv := &http.Server{
Addr: config.GetString("core.port"),
Handler: registry.GetRouter(),
}
lc.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
ln, err := net.Listen("tcp", srv.Addr)
if err != nil {
return err
}
go func() {
err := srv.Serve(ln)
if err != nil {
logger.Fatal("Failed to serve", zap.Error(err))
}
}()
return nil
},
OnStop: func(ctx context.Context) error {
return srv.Shutdown(ctx)
},
})
return srv, nil
}

View File

@ -58,33 +58,6 @@ func main() {
fx.Provide(api.NewCasbin), fx.Provide(api.NewCasbin),
fx.Invoke(protocols.SetupLifecycles), fx.Invoke(protocols.SetupLifecycles),
fx.Invoke(api.SetupLifecycles), fx.Invoke(api.SetupLifecycles),
fx.Provide(func(lc fx.Lifecycle, config *viper.Viper) *http.Server { fx.Provide(NewServer),
srv := &http.Server{
Addr: config.GetString("core.port"),
Handler: registry.GetRouter(),
}
lc.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
ln, err := net.Listen("tcp", srv.Addr)
if err != nil {
return err
}
go func() {
err := srv.Serve(ln)
if err != nil {
logger.Fatal("Failed to serve", zap.Error(err))
}
}()
return nil
},
OnStop: func(ctx context.Context) error {
return srv.Shutdown(ctx)
},
})
return srv
}),
).Run() ).Run()
} }