2017-11-09 15:12:04 +00:00
|
|
|
package ping
|
|
|
|
|
|
|
|
import (
|
2018-04-23 13:30:03 +00:00
|
|
|
"context"
|
2017-11-09 15:12:04 +00:00
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
|
2019-08-03 01:58:23 +00:00
|
|
|
"github.com/gorilla/mux"
|
2017-11-09 15:12:04 +00:00
|
|
|
)
|
|
|
|
|
2018-11-14 09:18:03 +00:00
|
|
|
// Handler expose ping routes.
|
2017-11-09 15:12:04 +00:00
|
|
|
type Handler struct {
|
2018-03-22 17:18:03 +00:00
|
|
|
terminating bool
|
|
|
|
}
|
|
|
|
|
2019-06-17 09:48:05 +00:00
|
|
|
// SetDefaults sets the default values.
|
|
|
|
func (h *Handler) SetDefaults() {
|
|
|
|
}
|
|
|
|
|
2018-04-23 13:30:03 +00:00
|
|
|
// WithContext causes the ping endpoint to serve non 200 responses.
|
|
|
|
func (h *Handler) WithContext(ctx context.Context) {
|
|
|
|
go func() {
|
|
|
|
<-ctx.Done()
|
|
|
|
h.terminating = true
|
|
|
|
}()
|
2017-11-09 15:12:04 +00:00
|
|
|
}
|
|
|
|
|
2018-11-14 09:18:03 +00:00
|
|
|
// Append adds ping routes on a router.
|
|
|
|
func (h *Handler) Append(router *mux.Router) {
|
2017-11-20 08:40:03 +00:00
|
|
|
router.Methods(http.MethodGet, http.MethodHead).Path("/ping").
|
2017-11-09 15:12:04 +00:00
|
|
|
HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
|
2018-03-22 17:18:03 +00:00
|
|
|
statusCode := http.StatusOK
|
2018-04-23 13:30:03 +00:00
|
|
|
if h.terminating {
|
2018-03-22 17:18:03 +00:00
|
|
|
statusCode = http.StatusServiceUnavailable
|
|
|
|
}
|
|
|
|
response.WriteHeader(statusCode)
|
|
|
|
fmt.Fprint(response, http.StatusText(statusCode))
|
2017-11-09 15:12:04 +00:00
|
|
|
})
|
|
|
|
}
|