go-web-template/handlers/healthcheck.go

78 lines
1.6 KiB
Go
Raw Permalink Normal View History

2024-08-25 16:40:48 +02:00
package handlers
import (
"encoding/json"
"fmt"
"net/http"
"runtime"
"time"
"github.com/rs/zerolog/hlog"
)
const (
jsonContentType = "application/json;charset=utf-8"
)
type Timing struct {
TimeMillis time.Duration `json:"timeMillis"`
Source string `json:"source"`
}
type HealthCheckResult struct {
Success bool `json:"success"`
Messages []string `json:"messages"`
Time time.Time `json:"time"`
Timing []Timing `json:"timing"`
Response HealthCheckResponse `json:"response"`
}
type HealthCheckResponse struct {
IpAddress string `json:"ipAddress"`
MemUsage string `json:"memUsage"`
}
func (app *Application) HealthCheck(w http.ResponseWriter, r *http.Request) {
l := hlog.FromRequest(r)
l.Info().Msg("HealthCheck")
start := time.Now()
t, _ := json.Marshal(HealthCheckResult{
Success: true,
Messages: []string{},
Time: time.Now().UTC(),
Timing: []Timing{
{
Source: "HealthCheck",
TimeMillis: time.Since(start),
},
},
Response: HealthCheckResponse{
IpAddress: getIP(r),
MemUsage: memUsage(),
},
})
w.Header().Set("content-type", jsonContentType)
_, _ = fmt.Fprint(w, string(t))
}
func getIP(r *http.Request) string {
// forwarded := r.Header.Get("X-FORWARDED-FOR")
// if forwarded != "" {
// return forwarded
// }
return r.RemoteAddr
}
func memUsage() string {
var m runtime.MemStats
runtime.ReadMemStats(&m)
result := fmt.Sprintf("memoryusage::Alloc = %v MB::TotalAlloc = %v MB::Sys = %v MB::tNumGC = %v", bToMb(m.Alloc), bToMb(m.TotalAlloc), bToMb(m.Sys), m.NumGC)
return result
}
func bToMb(b uint64) uint64 {
return b / 1024 / 1024
}