add helm chart with readiness endpoint
This commit is contained in:
32
main.go
32
main.go
@@ -3,7 +3,6 @@ package main
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
@@ -20,6 +19,28 @@ func dbConnection() (*sql.DB, error) {
|
||||
return sql.Open("postgres", connStr)
|
||||
}
|
||||
|
||||
// livenessHandler is used by Kubernetes to check if the app is alive.
|
||||
func livenessHandler(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
fmt.Fprintf(w, "OK")
|
||||
}
|
||||
|
||||
// readinessHandler is used by Kubernetes to check if the app is ready to serve traffic.
|
||||
func readinessHandler(w http.ResponseWriter, r *http.Request) {
|
||||
// Check if the database connection is alive
|
||||
err := db.Ping()
|
||||
if err != nil {
|
||||
log.Printf("Readiness probe failed: Database connection error: %v", err)
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
fmt.Fprintf(w, "NOT READY")
|
||||
return
|
||||
}
|
||||
|
||||
// If the database is reachable, return 200 OK
|
||||
w.WriteHeader(http.StatusOK)
|
||||
fmt.Fprintf(w, "OK")
|
||||
}
|
||||
|
||||
// indexHandler serves the HTML form for the query.
|
||||
func indexHandler(w http.ResponseWriter, r *http.Request) {
|
||||
tmpl := `
|
||||
@@ -70,8 +91,7 @@ func indexHandler(w http.ResponseWriter, r *http.Request) {
|
||||
</body>
|
||||
</html>
|
||||
`
|
||||
t := template.Must(template.New("form").Parse(tmpl))
|
||||
t.Execute(w, nil)
|
||||
fmt.Fprintf(w, tmpl)
|
||||
}
|
||||
|
||||
// selectHandler handles HTTP requests and executes a SQL query.
|
||||
@@ -122,6 +142,12 @@ func main() {
|
||||
// Define the handler for the `/query` route (executes SQL query)
|
||||
http.HandleFunc("/query", selectHandler)
|
||||
|
||||
// Define the handler for the `/liveness` probe
|
||||
http.HandleFunc("/liveness", livenessHandler)
|
||||
|
||||
// Define the handler for the `/readiness` probe
|
||||
http.HandleFunc("/readiness", readinessHandler)
|
||||
|
||||
// Start the HTTP server
|
||||
port := ":8080"
|
||||
log.Printf("Server starting on port %s\n", port)
|
||||
|
||||
Reference in New Issue
Block a user