-
-
Save xpzouying/763eb757fb821c3f2937e46797bdd142 to your computer and use it in GitHub Desktop.
go http server with graceful shutdown
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"flag" | |
"log" | |
"net/http" | |
"os" | |
"os/signal" | |
"time" | |
) | |
func main() { | |
log.SetFlags(0) | |
var listenAddress = flag.String("listen", ":8000", "Listen address.") | |
flag.Parse() | |
if flag.NArg() != 0 { | |
flag.Usage() | |
log.Fatalf("\nERROR You MUST NOT pass any positional arguments") | |
} | |
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { | |
log.Printf("HTTP %s %s%s\n", r.Method, r.Host, r.URL) | |
if r.URL.Path != "/" { | |
http.Error(w, "Not Found", http.StatusNotFound) | |
return | |
} | |
w.Header().Set("Content-Type", "text/plain") | |
w.Write([]byte(time.Now().Local().Format(time.RFC1123Z))) | |
}) | |
log.Printf("Listening at http://%s", *listenAddress) | |
httpServer := http.Server{ | |
Addr: *listenAddress, | |
} | |
idleConnectionsClosed := make(chan struct{}) | |
go func() { | |
sigint := make(chan os.Signal, 1) | |
signal.Notify(sigint, os.Interrupt) | |
<-sigint | |
if err := httpServer.Shutdown(context.Background()); err != nil { | |
log.Printf("HTTP Server Shutdown Error: %v", err) | |
} | |
close(idleConnectionsClosed) | |
}() | |
if err := httpServer.ListenAndServe(); err != http.ErrServerClosed { | |
log.Fatalf("HTTP server ListenAndServe Error: %v", err) | |
} | |
<-idleConnectionsClosed | |
log.Printf("Bye bye") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment