From 4e5e40f6f1e20fb20a9fabdd74ab19afe693775b Mon Sep 17 00:00:00 2001 From: Miguel de la Cruz Date: Sun, 12 Sep 2021 18:27:49 +0200 Subject: [PATCH] Complete server lifecycle --- cmd/rmsn/rmsn.go | 5 ++++- server/server.go | 17 +++++++++++------ web/web.go | 25 +++++++++++++++++++++---- 3 files changed, 36 insertions(+), 11 deletions(-) diff --git a/cmd/rmsn/rmsn.go b/cmd/rmsn/rmsn.go index 5685815..e2c6df4 100644 --- a/cmd/rmsn/rmsn.go +++ b/cmd/rmsn/rmsn.go @@ -25,7 +25,10 @@ func main() { go func() { fmt.Println("Starting rmsn") - srv.Start() // ToDo: this should be blocking + if err := srv.Start(); err != nil { + fmt.Fprintf(os.Stderr, "error running server: %s", err) + os.Exit(1) + } closed <- true }() diff --git a/server/server.go b/server/server.go index f874052..668d81f 100644 --- a/server/server.go +++ b/server/server.go @@ -2,7 +2,6 @@ package server import ( "fmt" - "net/http" "git.ctrlz.es/mgdelacroix/rmsn/model" "git.ctrlz.es/mgdelacroix/rmsn/services/store" @@ -13,7 +12,7 @@ type Server struct { Config *model.Config Store *store.Store - WebServer *http.Server + WebServer *web.WebServer } func NewServer(config *model.Config) (*Server, error) { @@ -48,14 +47,20 @@ func NewServerWithConfigPath(path string) (*Server, error) { } func (s *Server) Start() error { - // ToDo: start webserver here - + if err := s.WebServer.Start(); err != nil { + return fmt.Errorf("error starting webserver: %w", err) + } return nil } func (s *Server) Close() error { - // ToDo: stop webserver - // ToDo: close store + 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) + } return nil } diff --git a/web/web.go b/web/web.go index e5b969d..d813096 100644 --- a/web/web.go +++ b/web/web.go @@ -5,7 +5,11 @@ import ( "net/http" ) -func NewWebServer(port int) (*http.Server, error) { +type WebServer struct { + *http.Server +} + +func NewWebServer(port int) (*WebServer, error) { mux := http.NewServeMux() // ToDo: configure routes @@ -13,10 +17,23 @@ func NewWebServer(port int) (*http.Server, error) { fmt.Fprintf(w, "Hello rmsn!!") }) - s := &http.Server{ - Addr: fmt.Sprintf(":%d", port), - Handler: mux, + s := &WebServer{ + &http.Server{ + Addr: fmt.Sprintf(":%d", port), + Handler: mux, + }, } return s, nil } + +func (w *WebServer) Start() error { + if err := w.Server.ListenAndServe(); err != nil && err != http.ErrServerClosed { + return err + } + return nil +} + +func (w *WebServer) Close() error { + return w.Server.Close() +}