Created
May 26, 2019 05:04
-
-
Save prantoran/69d14842f0a350007ff35fbb540252d8 to your computer and use it in GitHub Desktop.
graceful-server
This file contains hidden or 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" | |
"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) | |
} | |
} |
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
the
err
variable is shadowed on line 44, making the check on line 50 a no-op