Skip to content

Instantly share code, notes, and snippets.

@shienyuan
Created January 30, 2021 10:45
Show Gist options
  • Save shienyuan/89d9e49e804193b0ea0c2e9c812cded3 to your computer and use it in GitHub Desktop.
Save shienyuan/89d9e49e804193b0ea0c2e9c812cded3 to your computer and use it in GitHub Desktop.
Go useful snippets
func main() {
// simple logger with time flag
l := log.New(os.Stdout, "", log.LstdFlags)
// handler
h := http.NewServeMux()
// h.Handle("/", handler.HelloWorld))
// sever with standard setups
s := http.Server{
Addr: addr,
Handler: h,
ErrorLog: l,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
}
// start the sever concurrently to not blocking below codes.
go func() {
l.Println("Sever running at", addr)
l.Fatal(s.ListenAndServe())
}()
// graceful shutdown on system interrup or kill
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, os.Kill)
// wait for signal
<-sig
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
defer cancel()
log.Println("Gracefully shutting down...")
// shutdown sever with 30 seconds timeout
_ = s.Shutdown(ctx)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment