github.com/mmrath/gobase@v0.0.1/client/app/server.go (about) 1 package app 2 3 import ( 4 "context" 5 "net/http" 6 "os" 7 "os/signal" 8 "strings" 9 10 "github.com/go-chi/chi" 11 "github.com/rs/zerolog/log" 12 "github.com/mmrath/gobase/client/account" 13 "github.com/mmrath/gobase/common/email" 14 "github.com/mmrath/gobase/model" 15 ) 16 17 // Server provides an http.Server. 18 type Server struct { 19 *http.Server 20 } 21 22 23 24 func NewDB(cfg Config) (*model.DB, error) { 25 return model.DBConn(cfg.DB) 26 } 27 28 func NewMailer(cfg Config) (email.Mailer, error) { 29 return email.NewMailer(cfg.SMTP) 30 } 31 32 func NewNotifier(cfg Config, mailer email.Mailer) account.Notifier { 33 return account.NewNotifier(cfg.Web.URL, mailer) 34 } 35 36 // NewServer creates and configures an APIServer serving all application routes. 37 func NewServer(cfg Config, mux *chi.Mux) (*Server, error) { 38 var addr string 39 port := cfg.Web.Port 40 41 if strings.Contains(port, ":") { 42 addr = port 43 } else { 44 addr = ":" + port 45 } 46 47 srv := http.Server{ 48 Addr: addr, 49 Handler: mux, 50 } 51 52 return &Server{&srv}, nil 53 } 54 55 // Start runs ListenAndServe on the http.Server with graceful shutdown. 56 func (srv *Server) Start() { 57 log.Print("starting server...") 58 go func() { 59 if err := srv.ListenAndServe(); err != http.ErrServerClosed { 60 panic(err) 61 } 62 }() 63 log.Printf("Listening on %s\n", srv.Addr) 64 65 quit := make(chan os.Signal) 66 signal.Notify(quit, os.Interrupt) 67 sig := <-quit 68 log.Print("shutting down server... reason:", sig) 69 70 if err := srv.Shutdown(context.Background()); err != nil { 71 panic(err) 72 } 73 log.Print("server gracefully stopped") 74 }