Complete server lifecycle

This commit is contained in:
Miguel de la Cruz 2021-09-12 18:27:49 +02:00
parent 19a2096193
commit 4e5e40f6f1
3 changed files with 36 additions and 11 deletions

View file

@ -25,7 +25,10 @@ func main() {
go func() { go func() {
fmt.Println("Starting rmsn") 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 closed <- true
}() }()

View file

@ -2,7 +2,6 @@ package server
import ( import (
"fmt" "fmt"
"net/http"
"git.ctrlz.es/mgdelacroix/rmsn/model" "git.ctrlz.es/mgdelacroix/rmsn/model"
"git.ctrlz.es/mgdelacroix/rmsn/services/store" "git.ctrlz.es/mgdelacroix/rmsn/services/store"
@ -13,7 +12,7 @@ type Server struct {
Config *model.Config Config *model.Config
Store *store.Store Store *store.Store
WebServer *http.Server WebServer *web.WebServer
} }
func NewServer(config *model.Config) (*Server, error) { func NewServer(config *model.Config) (*Server, error) {
@ -48,14 +47,20 @@ func NewServerWithConfigPath(path string) (*Server, error) {
} }
func (s *Server) Start() 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 return nil
} }
func (s *Server) Close() error { func (s *Server) Close() error {
// ToDo: stop webserver if err := s.WebServer.Close(); err != nil {
// ToDo: close store 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 return nil
} }

View file

@ -5,7 +5,11 @@ import (
"net/http" "net/http"
) )
func NewWebServer(port int) (*http.Server, error) { type WebServer struct {
*http.Server
}
func NewWebServer(port int) (*WebServer, error) {
mux := http.NewServeMux() mux := http.NewServeMux()
// ToDo: configure routes // ToDo: configure routes
@ -13,10 +17,23 @@ func NewWebServer(port int) (*http.Server, error) {
fmt.Fprintf(w, "Hello rmsn!!") fmt.Fprintf(w, "Hello rmsn!!")
}) })
s := &http.Server{ s := &WebServer{
&http.Server{
Addr: fmt.Sprintf(":%d", port), Addr: fmt.Sprintf(":%d", port),
Handler: mux, Handler: mux,
},
} }
return s, nil 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()
}