Skip to content

Instantly share code, notes, and snippets.

@prantoran
Created May 26, 2019 05:04
Show Gist options
  • Save prantoran/69d14842f0a350007ff35fbb540252d8 to your computer and use it in GitHub Desktop.
Save prantoran/69d14842f0a350007ff35fbb540252d8 to your computer and use it in GitHub Desktop.
graceful-server
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"time"
)
func serve(ctx context.Context) (err error) {
mux := http.NewServeMux()
mux.Handle("/", http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "okay")
},
))
srv := &http.Server{
Addr: ":6969",
Handler: mux,
}
go func() {
if err = srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen:%+s\n", err)
}
}()
log.Printf("server started")
<-ctx.Done()
log.Printf("server stopped")
ctxShutDown, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer func() {
cancel()
}()
if err = srv.Shutdown(ctxShutDown); err != nil {
log.Fatalf("server Shutdown Failed:%+s", err)
}
log.Printf("server exited properly")
if err == http.ErrServerClosed {
err = nil
}
return
}
func main() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
ctx, cancel := context.WithCancel(context.Background())
go func() {
oscall := <-c
log.Printf("system call:%+v", oscall)
cancel()
}()
if err := serve(ctx); err != nil {
log.Printf("failed to serve:+%v\n", err)
}
}
@b5
Copy link

b5 commented Jul 8, 2020

the err variable is shadowed on line 44, making the check on line 50 a no-op

@prantoran
Copy link
Author

Well, I don't think there are any variable shadowing since the variable err is declared once in the function declaration. Declaration of variables is with :=.

Though, there could be assignment error as both the go function in 27 and the shutdown error check in line 44 are using the err. The go function is listening to server requests and assign errors after a connection event has occurred, while the assignment in line 44 is performed once. There could be an overlap of assignments.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment