arcast/pkg/server/server.go

114 lines
2.2 KiB
Go
Raw Normal View History

2023-12-13 20:07:22 +01:00
package server
import (
"context"
"crypto/tls"
2024-04-26 12:10:59 +02:00
"io/fs"
2023-12-13 20:07:22 +01:00
"forge.cadoles.com/arcad/arcast/pkg/browser"
2024-04-24 17:32:01 +02:00
"github.com/gorilla/websocket"
2023-12-13 20:07:22 +01:00
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/logger"
)
type Server struct {
browser browser.Browser
instanceID string
address string
port int
tlsAddress string
tlsPort int
tlsCert *tls.Certificate
serviceDiscoveryEnabled bool
2024-04-24 17:32:01 +02:00
appsEnabled bool
defaultApp string
allowedOrigins []string
apps []App
2023-12-13 20:07:22 +01:00
2024-04-24 17:32:01 +02:00
ctx context.Context
cancel context.CancelFunc
upgrader websocket.Upgrader
2024-04-26 12:10:59 +02:00
layeredFS fs.FS
upperLayerDir string
2023-12-13 20:07:22 +01:00
}
func (s *Server) Start() error {
2024-04-26 12:10:59 +02:00
ctx := context.Background()
if err := s.initLayeredFS(); err != nil {
return errors.WithStack(err)
}
serverCtx, cancelServer := context.WithCancel(ctx)
2023-12-13 20:07:22 +01:00
s.cancel = cancelServer
s.ctx = serverCtx
webServersCtx, cancelWebServers := context.WithCancel(serverCtx)
if err := s.startWebServers(webServersCtx); err != nil {
cancelWebServers()
2023-12-13 20:07:22 +01:00
return errors.WithStack(err)
}
if s.serviceDiscoveryEnabled {
2023-12-13 20:07:22 +01:00
mdnsServerCtx, cancelMDNSServer := context.WithCancel(serverCtx)
if err := s.startMDNServer(mdnsServerCtx); err != nil {
cancelWebServers()
2023-12-13 20:07:22 +01:00
cancelMDNSServer()
return errors.WithStack(err)
}
} else {
logger.Info(serverCtx, "service discovery disabled")
}
return nil
}
func (s *Server) Stop() error {
if s.cancel != nil {
s.cancel()
}
return nil
}
func (s *Server) Wait() error {
<-s.ctx.Done()
if err := s.ctx.Err(); err != nil {
return errors.WithStack(err)
}
return nil
}
func New(browser browser.Browser, funcs ...OptionFunc) *Server {
opts := NewOptions(funcs...)
2024-04-24 17:32:01 +02:00
server := &Server{
2023-12-13 20:07:22 +01:00
browser: browser,
instanceID: opts.InstanceID,
address: opts.Address,
tlsAddress: opts.TLSAddress,
tlsCert: opts.TLSCertificate,
appsEnabled: opts.EnableApps,
2024-04-24 17:32:01 +02:00
allowedOrigins: opts.AllowedOrigins,
defaultApp: opts.DefaultApp,
apps: opts.Apps,
serviceDiscoveryEnabled: opts.EnableServiceDiscovery,
2024-04-26 12:10:59 +02:00
upperLayerDir: opts.UpperLayerDir,
2023-12-13 20:07:22 +01:00
}
2024-04-24 17:32:01 +02:00
server.upgrader = websocket.Upgrader{
CheckOrigin: server.checkOrigin,
}
return server
2023-12-13 20:07:22 +01:00
}