http/health: remove health handler (#978)

* remove health handler & example
pull/979/head
Tony Chen 4 years ago committed by GitHub
parent ad8f12c9fd
commit f83438b693
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 34
      examples/http/health/main.go
  2. 66
      transport/http/health/health.go

@ -1,34 +0,0 @@
package main
import (
"context"
"errors"
"log"
"github.com/go-kratos/kratos/v2"
"github.com/go-kratos/kratos/v2/transport/http"
"github.com/go-kratos/kratos/v2/transport/http/health"
)
func main() {
handler := health.NewHandler()
handler.AddChecker("mysql", func(ctx context.Context) error {
return nil
})
handler.AddObserver("redis", func(ctx context.Context) error {
return errors.New("connection refused")
})
httpSrv := http.NewServer(http.Address(":8000"))
httpSrv.Handle("/healthz", handler)
app := kratos.New(
kratos.Name("mux"),
kratos.Server(
httpSrv,
),
)
if err := app.Run(); err != nil {
log.Println(err)
}
}

@ -1,66 +0,0 @@
package health
import (
"context"
"encoding/json"
"net/http"
)
// CheckerFunc wraps the CheckHealth method.
//
// CheckHealth returns nil if the resource is healthy, or a non-nil
// error if the resource is not healthy. CheckHealth must be safe to
// call from multiple goroutines.
type CheckerFunc func(ctx context.Context) error
// Handler is an HTTP handler that reports on the success of an
// aggregate of Checkers. The zero value is always healthy.
type Handler struct {
checkers map[string]CheckerFunc
observers map[string]CheckerFunc
}
// NewHandler new a health handler.
func NewHandler() *Handler {
return &Handler{
checkers: make(map[string]CheckerFunc),
observers: make(map[string]CheckerFunc),
}
}
// AddChecker adds a new check to the handler.
func (h *Handler) AddChecker(name string, c CheckerFunc) {
h.checkers[name] = c
}
// AddObserver adds a new check to the handler but it does not fail the entire status.
func (h *Handler) AddObserver(name string, c CheckerFunc) {
h.observers[name] = c
}
// ServeHTTP returns 200 if it is healthy, 500 otherwise.
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
code := http.StatusOK
results := make(map[string]string, len(h.checkers))
for name, checker := range h.checkers {
if err := checker(r.Context()); err != nil {
code = http.StatusInternalServerError
results[name] = err.Error()
} else {
results[name] = "OK"
}
}
for name, checker := range h.observers {
if err := checker(r.Context()); err != nil {
results[name] = err.Error()
} else {
results[name] = "OK"
}
}
w.WriteHeader(code)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(w).Encode(results)
}
Loading…
Cancel
Save