2016-04-06 09:21:46 +01:00
|
|
|
package health
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"io"
|
|
|
|
|
"log"
|
2016-04-29 07:28:35 +01:00
|
|
|
"net"
|
2016-04-06 09:21:46 +01:00
|
|
|
"net/http"
|
|
|
|
|
"sync"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
var once sync.Once
|
|
|
|
|
|
2016-09-23 09:14:12 +01:00
|
|
|
type health struct {
|
2016-04-06 09:21:46 +01:00
|
|
|
Addr string
|
2016-08-19 17:14:17 -07:00
|
|
|
|
|
|
|
|
ln net.Listener
|
|
|
|
|
mux *http.ServeMux
|
2016-04-06 09:21:46 +01:00
|
|
|
}
|
|
|
|
|
|
2016-09-23 09:14:12 +01:00
|
|
|
func (h *health) Startup() error {
|
2016-04-06 09:21:46 +01:00
|
|
|
if h.Addr == "" {
|
|
|
|
|
h.Addr = defAddr
|
|
|
|
|
}
|
2016-04-29 07:28:35 +01:00
|
|
|
|
2016-04-06 09:21:46 +01:00
|
|
|
once.Do(func() {
|
2016-09-23 09:14:12 +01:00
|
|
|
ln, err := net.Listen("tcp", h.Addr)
|
|
|
|
|
if err != nil {
|
2016-04-29 07:28:35 +01:00
|
|
|
log.Printf("[ERROR] Failed to start health handler: %s", err)
|
|
|
|
|
return
|
|
|
|
|
}
|
2016-09-23 09:14:12 +01:00
|
|
|
|
|
|
|
|
h.ln = ln
|
|
|
|
|
|
2016-04-29 07:28:35 +01:00
|
|
|
h.mux = http.NewServeMux()
|
|
|
|
|
|
2016-09-23 09:14:12 +01:00
|
|
|
h.mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
io.WriteString(w, ok)
|
|
|
|
|
})
|
|
|
|
|
|
2016-04-06 09:21:46 +01:00
|
|
|
go func() {
|
2016-04-29 07:28:35 +01:00
|
|
|
http.Serve(h.ln, h.mux)
|
2016-04-06 09:21:46 +01:00
|
|
|
}()
|
|
|
|
|
})
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2016-09-23 09:14:12 +01:00
|
|
|
func (h *health) Shutdown() error {
|
2016-04-29 07:28:35 +01:00
|
|
|
if h.ln != nil {
|
|
|
|
|
return h.ln.Close()
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2016-04-06 09:21:46 +01:00
|
|
|
const (
|
|
|
|
|
ok = "OK"
|
|
|
|
|
defAddr = ":8080"
|
2016-04-29 07:28:35 +01:00
|
|
|
path = "/health"
|
2016-04-06 09:21:46 +01:00
|
|
|
)
|