whatismyip/server/server.go

97 lines
1.6 KiB
Go
Raw Normal View History

2023-03-20 15:33:45 +00:00
package server
import (
"log"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/dcarrillo/whatismyip/internal/setting"
"github.com/dcarrillo/whatismyip/models"
"golang.org/x/net/context"
)
type Server interface {
Start()
Stop()
}
type Factory struct {
tcpServer *TCPServer
tlsServer *TLSServer
quicServer *QuicServer
}
func Setup(ctx context.Context, handler http.Handler) *Factory {
var tcpServer *TCPServer
var tlsServer *TLSServer
var quicServer *QuicServer
2023-03-20 15:33:45 +00:00
if setting.App.BindAddress != "" {
tcpServer = NewTCPServer(ctx, &handler)
}
if setting.App.TLSAddress != "" {
tlsServer = NewTLSServer(ctx, &handler)
if setting.App.EnableHTTP3 {
quicServer = NewQuicServer(ctx, tlsServer)
2023-03-20 15:33:45 +00:00
}
}
return &Factory{
tcpServer: tcpServer,
tlsServer: tlsServer,
quicServer: quicServer,
2023-03-20 15:33:45 +00:00
}
}
2023-03-21 19:19:11 +00:00
func (f *Factory) Run() {
f.start()
2023-03-20 15:33:45 +00:00
signalChan := make(chan os.Signal, 3)
signal.Notify(signalChan, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM)
var s os.Signal
for {
s = <-signalChan
if s == syscall.SIGHUP {
2023-03-21 19:19:11 +00:00
f.stop()
2023-03-20 15:33:45 +00:00
models.CloseDBs()
models.Setup(setting.App.GeodbPath.City, setting.App.GeodbPath.ASN)
2023-03-21 19:19:11 +00:00
f.start()
2023-03-20 15:33:45 +00:00
} else {
log.Printf("Shutting down...")
2023-03-21 19:19:11 +00:00
f.stop()
2023-03-20 15:33:45 +00:00
models.CloseDBs()
break
}
}
}
2023-03-21 19:19:11 +00:00
func (f *Factory) start() {
if f.tcpServer != nil {
f.tcpServer.Start()
2023-03-20 15:33:45 +00:00
}
2023-03-21 19:19:11 +00:00
if f.tlsServer != nil {
f.tlsServer.Start()
if f.quicServer != nil {
f.quicServer.Start()
2023-03-20 15:33:45 +00:00
}
}
}
2023-03-21 19:19:11 +00:00
func (f *Factory) stop() {
if f.tcpServer != nil {
f.tcpServer.Stop()
2023-03-20 15:33:45 +00:00
}
2023-03-21 19:19:11 +00:00
if f.tlsServer != nil {
if f.quicServer != nil {
f.quicServer.Stop()
2023-03-20 15:33:45 +00:00
}
2023-03-21 19:19:11 +00:00
f.tlsServer.Stop()
2023-03-20 15:33:45 +00:00
}
}