Controller can register functions to run at shutdown

This commit is contained in:
Matthew Holt 2015-03-26 23:22:48 -06:00
parent 1146a9b90b
commit da72a5fbcd
3 changed files with 9 additions and 2 deletions

View File

@ -28,6 +28,11 @@ func (c *controller) Startup(fn func() error) {
c.parser.cfg.Startup = append(c.parser.cfg.Startup, fn) c.parser.cfg.Startup = append(c.parser.cfg.Startup, fn)
} }
// Shutdown registers a function to execute when the server exits.
func (c *controller) Shutdown(fn func() error) {
c.parser.cfg.Shutdown = append(c.parser.cfg.Shutdown, fn)
}
// Root returns the server root file path. // Root returns the server root file path.
func (c *controller) Root() string { func (c *controller) Root() string {
if c.parser.cfg.Root == "" { if c.parser.cfg.Root == "" {

View File

@ -71,6 +71,9 @@ type (
// Startup registers a function to execute when the server starts. // Startup registers a function to execute when the server starts.
Startup(func() error) Startup(func() error)
// Shutdown registers a function to execute when the server exits.
Shutdown(func() error)
// Root returns the file path from which the server is serving. // Root returns the file path from which the server is serving.
Root() string Root() string

View File

@ -78,7 +78,6 @@ func (s *Server) Serve() error {
http2.ConfigureServer(server, nil) // TODO: This may not be necessary after HTTP/2 merged into std lib http2.ConfigureServer(server, nil) // TODO: This may not be necessary after HTTP/2 merged into std lib
// Execute shutdown commands on exit // Execute shutdown commands on exit
// TODO: Is graceful net/http shutdown necessary?
go func() { go func() {
interrupt := make(chan os.Signal, 1) interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt, os.Kill) // TODO: syscall.SIGQUIT? (Ctrl+\, Unix-only) signal.Notify(interrupt, os.Interrupt, os.Kill) // TODO: syscall.SIGQUIT? (Ctrl+\, Unix-only)
@ -103,7 +102,7 @@ func (s *Server) Serve() error {
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer func() { defer func() {
if rec := recover(); rec != nil { if rec := recover(); rec != nil {
log.Printf("[PANIC] '%s': %s", r.URL.String(), rec) s.Log("[PANIC] '%s': %s", r.URL.String(), rec)
} }
}() }()
s.stack(w, r) s.stack(w, r)