2021-09-11 23:06:03 +01:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"git.ctrlz.es/mgdelacroix/rmsn/model"
|
2021-09-11 23:32:07 +01:00
|
|
|
"git.ctrlz.es/mgdelacroix/rmsn/services/store"
|
|
|
|
"git.ctrlz.es/mgdelacroix/rmsn/web"
|
2021-09-11 23:06:03 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
type Server struct {
|
|
|
|
Config *model.Config
|
2021-09-11 23:32:07 +01:00
|
|
|
|
|
|
|
Store *store.Store
|
2021-09-12 17:27:49 +01:00
|
|
|
WebServer *web.WebServer
|
2021-09-11 23:06:03 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewServer(config *model.Config) (*Server, error) {
|
|
|
|
if err := config.IsValid(); err != nil {
|
|
|
|
return nil, fmt.Errorf("config is not valid: %w", err)
|
|
|
|
}
|
|
|
|
|
2021-09-11 23:32:07 +01:00
|
|
|
webserver, err := web.NewWebServer(*config.Port)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("cannot create webserver: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
store, err := store.NewStore(*config.DatabasePath)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("cannot create store: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return &Server{
|
|
|
|
Config: config,
|
|
|
|
WebServer: webserver,
|
|
|
|
Store: store,
|
|
|
|
}, err
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewServerWithConfigPath(path string) (*Server, error) {
|
|
|
|
config, err := model.ReadConfig(path)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("cannot read config from path %q: %w", path, err)
|
|
|
|
}
|
2021-09-11 23:06:03 +01:00
|
|
|
|
2021-09-11 23:32:07 +01:00
|
|
|
return NewServer(config)
|
2021-09-11 23:06:03 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) Start() error {
|
2021-09-12 17:27:49 +01:00
|
|
|
if err := s.WebServer.Start(); err != nil {
|
|
|
|
return fmt.Errorf("error starting webserver: %w", err)
|
|
|
|
}
|
2021-09-11 23:06:03 +01:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) Close() error {
|
2021-09-12 17:27:49 +01:00
|
|
|
if err := s.WebServer.Close(); err != nil {
|
|
|
|
return fmt.Errorf("error stopping webserver: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := s.Store.Close(); err != nil {
|
|
|
|
return fmt.Errorf("error stopping store: %w", err)
|
|
|
|
}
|
2021-09-11 23:32:07 +01:00
|
|
|
|
2021-09-11 23:06:03 +01:00
|
|
|
return nil
|
|
|
|
}
|