Implement health checks by exposing an HTTP endpoint that returns a 200 OK status only when all critical dependencies are available.
package main
import (
"database/sql"
"net/http"
"os"
)
var db *sql.DB
func main() {
// Initialize DB connection (pseudo-code)
// db, _ = sql.Open("postgres", os.Getenv("DB_URL"))
http.HandleFunc("/health", healthHandler)
http.ListenAndServe(":8080", nil)
}
func healthHandler(w http.ResponseWriter, r *http.Request) {
if err := db.Ping(); err != nil {
http.Error(w, "DB connection failed", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}