func listenHTTPHealth()

in grpc-xds/greeter-go/pkg/server/http_health.go [28:54]


func listenHTTPHealth(logger logr.Logger, listener net.Listener, healthServer *health.Server) error {
	mux := http.NewServeMux()
	mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
		service := r.URL.Query().Get("service") // optional
		logger.Info("Received HTTP request", "url", r.URL.String(), "service", service, "remoteAddr", r.RemoteAddr, "headers", r.Header)
		healthResp, err := healthServer.Check(r.Context(), &healthpb.HealthCheckRequest{
			Service: service,
		})
		if err != nil {
			logger.Error(err, "could not access health status", "service", service)
			w.WriteHeader(http.StatusNotFound)
			w.Write([]byte(service))
			return
		}
		healthStatusCode := healthResp.GetStatus()
		healthStatusName := healthpb.HealthCheckResponse_ServingStatus_name[int32(healthStatusCode)]
		if healthStatusCode == healthpb.HealthCheckResponse_SERVING {
			w.WriteHeader(http.StatusOK)
			w.Write([]byte(healthStatusName))
			return
		}
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte(healthStatusName))
	})
	httpHealthServer := &http.Server{Handler: h2c.NewHandler(mux, &http2.Server{})}
	return httpHealthServer.Serve(listener)
}