github.com/msales/pkg/v3@v3.24.0/health/handler.go (about)

     1  package health
     2  
     3  import (
     4  	"net/http"
     5  )
     6  
     7  // Null is the null Health reporter.
     8  func Null() ReporterFunc {
     9  	return func() error {
    10  		return nil
    11  	}
    12  }
    13  
    14  // Reporter represents an a health reporter.
    15  type Reporter interface {
    16  	// IsHealthy emits error if application is not healthy.
    17  	IsHealthy() error
    18  }
    19  
    20  // ReporterFunc is an adapter for anonymous functions to be used as health reporters.
    21  type ReporterFunc func() error
    22  
    23  // IsHealthy emits error if application is not healthy.
    24  func (f ReporterFunc) IsHealthy() error {
    25  	return f()
    26  }
    27  
    28  // Handler is an http health handler.
    29  type Handler struct {
    30  	reporters []Reporter
    31  	showErr   bool
    32  }
    33  
    34  // NewHandler creates a new Handler instance.
    35  func NewHandler() *Handler {
    36  	return &Handler{}
    37  }
    38  
    39  // With adds reports to the handler.
    40  func (h *Handler) With(reporters ...Reporter) *Handler {
    41  	h.reporters = append(h.reporters, reporters...)
    42  	return h
    43  }
    44  
    45  // WithErrors configures the handler to show the error message
    46  // in the response.
    47  func (h *Handler) WithErrors() *Handler {
    48  	h.showErr = true
    49  	return h
    50  }
    51  
    52  // ServeHTTP serves an http request.
    53  func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    54  	for _, reporter := range h.reporters {
    55  		if err := reporter.IsHealthy(); err != nil {
    56  			http.Error(w, h.getResponseContent(err), http.StatusServiceUnavailable)
    57  			return
    58  		}
    59  	}
    60  
    61  	w.WriteHeader(http.StatusOK)
    62  }
    63  
    64  func (h *Handler) getResponseContent(err error) string {
    65  	if h.showErr {
    66  		return err.Error()
    67  	}
    68  
    69  	return http.StatusText(http.StatusServiceUnavailable)
    70  }