Skip to content

Instantly share code, notes, and snippets.

@acoshift
Created April 7, 2018 11:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acoshift/4c8825867bc9033478f02ede3f10762c to your computer and use it in GitHub Desktop.
Save acoshift/4c8825867bc9033478f02ede3f10762c to your computer and use it in GitHub Desktop.
main.go for k8s app
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
func main() {
srv := &http.Server{
Addr: ":8080",
// ...
}
go func() {
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
log.Fatal(err)
}
}()
var (
ready = true
muReady sync.RWMutex
)
// health check
go func() {
m := http.NewServeMux()
m.HandleFunc("/readiness", func(w http.ResponseWriter, r *http.Request) {
muReady.RLock()
ready := ready
muReady.RUnlock()
if ready {
w.WriteHeader(http.StatusOK)
return
}
w.WriteHeader(http.StatusServiceUnavailable)
})
m.HandleFunc("/liveness", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
if err := http.ListenAndServe(":18080", m); err != nil {
log.Println("can not start healthcheck server")
}
}()
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGTERM)
<-stop
muReady.Lock()
ready = false
muReady.Unlock()
time.Sleep(5 * time.Second) // >= periodSeconds * failureThreshold
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Println("server shutdown error:", err)
return
}
log.Println("server shutdown")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment