Skip to content

Instantly share code, notes, and snippets.

@stefpe
Created August 1, 2018 13:02
Show Gist options
  • Save stefpe/c2a342f7f77ad5377f064bd0eac30318 to your computer and use it in GitHub Desktop.
Save stefpe/c2a342f7f77ad5377f064bd0eac30318 to your computer and use it in GitHub Desktop.
golang healthcheck example
package main
import (
"database/sql"
"encoding/json"
"fmt"
"net/http"
_ "github.com/go-sql-driver/mysql"
)
type HealthState struct {
State int
ErrorMessages []string
}
func main() {
http.HandleFunc("/healthcheck", handleRequest)
http.ListenAndServe(":3001", nil)
}
func handleRequest(w http.ResponseWriter, r *http.Request) {
outputState := &HealthState{}
checkWeb(outputState)
checkMysql(outputState)
if len(outputState.ErrorMessages) > 0 {
outputState.State = http.StatusServiceUnavailable
} else {
outputState.State = http.StatusOK
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(outputState.State)
json.NewEncoder(w).Encode(outputState)
}
func checkWeb(outputState *HealthState) {
resp, err := http.Get("https://medium.com")
if err != nil || resp.StatusCode < 200 || resp.StatusCode > 299 {
outputState.ErrorMessages = append(outputState.ErrorMessages, fmt.Sprintf("WebUI: %s", err.Error()))
}
}
func checkMysql(outputState *HealthState) {
db, err := sql.Open("mysql", "user:pass@tcp(127.0.0.1:3306)/dbname")
if err != nil {
outputState.ErrorMessages = append(outputState.ErrorMessages, fmt.Sprintf("MYSQL: %s", err.Error()))
} else {
defer db.Close()
}
err = db.Ping()
if err != nil {
outputState.ErrorMessages = append(outputState.ErrorMessages, fmt.Sprintf("MYSQL: %s", err.Error()))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment