diff --git a/internal/health/controller.go b/internal/health/controller.go new file mode 100644 index 0000000..1116a80 --- /dev/null +++ b/internal/health/controller.go @@ -0,0 +1,7 @@ +package health + +import "go.mongodb.org/mongo-driver/v2/mongo" + +type HealthController struct { + DB *mongo.Client +} diff --git a/internal/health/get.go b/internal/health/get.go new file mode 100644 index 0000000..5e4182d --- /dev/null +++ b/internal/health/get.go @@ -0,0 +1,17 @@ +package health + +import ( + "context" + "net/http" + + "github.com/gin-gonic/gin" +) + +func (hc *HealthController) Get(c *gin.Context) { + err := hc.DB.Ping(context.TODO(), nil) + if err != nil { + c.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{"error": "Database connection is down"}) + return + } + c.Status(http.StatusOK) +} diff --git a/main.go b/main.go index fa2a8dd..36687ff 100644 --- a/main.go +++ b/main.go @@ -8,6 +8,7 @@ import ( "github.com/SnackLog/database-api-wrapper/internal/config" "github.com/SnackLog/database-api-wrapper/internal/database" "github.com/SnackLog/database-api-wrapper/internal/handlers/product" + "github.com/SnackLog/database-api-wrapper/internal/health" serviceConfigLib "github.com/SnackLog/service-config-lib" "github.com/gin-gonic/gin" "go.mongodb.org/mongo-driver/v2/mongo" @@ -55,13 +56,21 @@ func disconnectDatabase(client *mongo.Client) { func setupRouter(db *mongo.Client) *gin.Engine { r := gin.Default() - products := r.Group("/products") + setupHealthCheckEndpoint(db, r) + products := r.Group("/products") setupEndpoints(products, db) return r } +func setupHealthCheckEndpoint(db *mongo.Client, router *gin.Engine) { + hc := &health.HealthController{ + DB: db, + } + router.GET("/health", hc.Get) +} + func setupEndpoints(router *gin.RouterGroup, db *mongo.Client) { productController := &product.ProductController{DB: db}