1
0
Fork 0

Health check data in another file

master
Ambrose Chua 2018-02-26 23:11:34 +08:00
parent aa53d019b3
commit 5e7236ef42
3 changed files with 38 additions and 23 deletions

View File

@ -43,12 +43,11 @@ func (h *Handlers) Get(w http.ResponseWriter, r *http.Request, p httprouter.Para
// Get the short URL
url, err := h.store.Get(p.ByName("id"))
if err != nil {
// Respond to health checks
if p.ByName("id") == "healthz" {
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("ok"))
return
}
// Respond to health checks
if p.ByName("id") == "healthz" {
healthz(w)
return
}
if err != sql.ErrNoRows {
log.Print("handlers: " + err.Error())
}

16
healthz.go Normal file
View File

@ -0,0 +1,16 @@
package main
import (
"fmt"
"net/http"
"runtime"
)
var ver string
func healthz(w http.ResponseWriter) {
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintf(w, "ok\n")
fmt.Fprintf(w, "ver: %v\n", ver)
fmt.Fprintf(w, "go ver: %v\n", runtime.Version())
}

34
main.go
View File

@ -31,14 +31,14 @@ func main() {
baseUrl = fmt.Sprintf("localhost:%d", port)
}
// Perform health check on running instance
if healthCheck {
err := ping()
if err != nil {
panic(err)
}
return
}
// Perform health check on running instance
if healthCheck {
err := ping()
if err != nil {
panic(err)
}
return
}
// Open database connection
db, err := sql.Open("postgres", postgres)
@ -59,13 +59,13 @@ func main() {
}
func ping() error {
resp, err := http.Get(fmt.Sprintf("http://localhost:%d/healthz", port))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("agent returned non-200 status code")
}
return nil
resp, err := http.Get(fmt.Sprintf("http://localhost:%d/healthz", port))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("agent returned non-200 status code")
}
return nil
}