» Go: Build a REST API with Gin » 2. Development » 2.2 Health Endpoint

Health Endpoint

A health endpoint refers to a specific endpoint or route provided by the server that is used to determine the health or status of the server or application. This endpoint is typically used for monitoring and management purposes, allowing external systems or monitoring tools to check whether the API server is functioning properly.

Modify main.go:

package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

func main() {
	// Create a new Gin router
	router := gin.Default()

	// Define a health endpoint handler, use `/health` or `/`
	router.GET("/", func(c *gin.Context) {
		// Return a simple response indicating the server is healthy
		c.JSON(http.StatusOK, gin.H{
			"status": "ok",
		})
	})

	// Run the server on port 8080
	router.Run(":8080")
}

The response of endpoint /:

{"status":"ok"}

Optional:
If you want to include CPU or memory data in the health endpoint response, you would need to gather this information from the system where your Go application is running.

Modify main.go [optional]:

@@ -2,6 +2,7 @@ package main
 
 import (
        "net/http"
+       "runtime"
 
        "github.com/gin-gonic/gin"
 )
@@ -12,9 +13,20 @@ func main() {
 
        // Define a health endpoint handler
        router.GET("/", func(c *gin.Context) {
+               // Get memory usage
+               var m runtime.MemStats
+               runtime.ReadMemStats(&m)
+               // Get CPU usage
+               // You can't directly get CPU usage in Go runtime, you can consider using an external library
+               // e.g. https://github.com/shirou/gopsutil
+               cpuUsage := 50.0 // placeholder
+
                // Return a simple response indicating the server is healthy
                c.JSON(http.StatusOK, gin.H{
-                       "status": "ok",
+                       "status":      "ok",
+                       "memory_byte": m.Alloc,
+                       "memory_MB":   m.Alloc / 1024 / 1024,
+                       "cpu_usage":   cpuUsage,
                })
        })

The response is something like this:

{"cpu_usage":50,"memory_MB":2,"memory_byte":3049016,"status":"ok"}
PrevNext