How do I add health and readiness endpoints in Go?

In Go, you can implement health and readiness endpoints as part of your web server to monitor the status of your application. These endpoints are commonly used in microservices environments and Kubernetes applications to ensure that your application is running smoothly and is ready to handle requests.

Health Endpoint

The health endpoint is used to check if the application is alive and functioning. A simple "/health" endpoint can return a 200 OK response.

Readiness Endpoint

The readiness endpoint checks if the application is ready to handle traffic. A "/readiness" endpoint might return a 200 OK response when the application is prepared to accept requests.

Example Implementation

package main import ( "fmt" "net/http" ) func healthHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) fmt.Fprintln(w, "OK") } func readinessHandler(w http.ResponseWriter, r *http.Request) { // You can add more checks here w.WriteHeader(http.StatusOK) fmt.Fprintln(w, "Ready") } func main() { http.HandleFunc("/health", healthHandler) http.HandleFunc("/readiness", readinessHandler) fmt.Println("Starting server on :8080") http.ListenAndServe(":8080", nil) }

Go health endpoint Go readiness endpoint Go web server microservices health checks Kubernetes readiness probes