From 2bb69033e5a9f01b9b255f7cca473cbc5ce598aa Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Fri, 17 Jan 2020 05:48:39 -0800 Subject: [PATCH] http: fail appropriately and return standard Go error (#8837) return http.ErrServerClosed with proper body when server is shutting down, allowing more context instead of just returning '503' which doesn't mean the same thing. --- cmd/http/server.go | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/cmd/http/server.go b/cmd/http/server.go index 836f6bb12..092d279f8 100644 --- a/cmd/http/server.go +++ b/cmd/http/server.go @@ -87,15 +87,19 @@ func (srv *Server) Start() (err error) { // Wrap given handler to do additional // * return 503 (service unavailable) if the server in shutdown. wrappedHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - atomic.AddInt32(&srv.requestCount, 1) - defer atomic.AddInt32(&srv.requestCount, -1) - - // If server is in shutdown, return 503 (service unavailable) + // If server is in shutdown. if atomic.LoadUint32(&srv.inShutdown) != 0 { - w.WriteHeader(http.StatusServiceUnavailable) + // To indicate disable keep-alives + w.Header().Set("Connection", "close") + w.WriteHeader(http.StatusForbidden) + w.Write([]byte(http.ErrServerClosed.Error())) + w.(http.Flusher).Flush() return } + atomic.AddInt32(&srv.requestCount, 1) + defer atomic.AddInt32(&srv.requestCount, -1) + // Handle request using passed handler. handler.ServeHTTP(w, r) }) @@ -117,13 +121,13 @@ func (srv *Server) Shutdown() error { srv.listenerMutex.Lock() if srv.listener == nil { srv.listenerMutex.Unlock() - return errors.New("server not initialized") + return http.ErrServerClosed } srv.listenerMutex.Unlock() if atomic.AddUint32(&srv.inShutdown, 1) > 1 { // shutdown in progress - return errors.New("http server already in shutdown") + return http.ErrServerClosed } // Close underneath HTTP listener.