Skip to content

Commit

Permalink
feat: ping_mongodb
Browse files Browse the repository at this point in the history
  • Loading branch information
yzqzss committed May 25, 2024
1 parent d454984 commit 0c0d7f1
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 6 deletions.
9 changes: 3 additions & 6 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,6 @@ func connect_to_mongodb() {
fmt.Println("Connected to MongoDB!")
}

func ping(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
}

func init() {
connect_to_mongodb()
}
Expand All @@ -48,6 +42,9 @@ func main() {
r.GET("/ping", ping)
r.HEAD("/ping", ping)

r.GET("/ping_mongodb", ping_mongodb)
r.HEAD("/ping_mongodb", ping_mongodb)

v1_tracker := r.Group("/v1")
{
v1_tracker.POST("/projects", v1_projects)
Expand Down
69 changes: 69 additions & 0 deletions ping.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package main

import (
"context"
"time"

"github.com/gin-gonic/gin"
"go.mongodb.org/mongo-driver/mongo/readpref"
)

func ping(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
}

func ping_mongodb_primary() (time.Duration, error) {
PrimaryStartTime := time.Now()
// ping primary
PrimaryErr := mongoClient.Ping(context.Background(), readpref.Primary())
PrimaryEalapsedTime := time.Since(PrimaryStartTime)

return PrimaryEalapsedTime, PrimaryErr
}

func ping_mongodb_nearest() (time.Duration, error) {
NearestStartTime := time.Now()
// ping nearest
NearestErr := mongoClient.Ping(context.Background(), readpref.Nearest())
NearestEalapsedTime := time.Since(NearestStartTime)

return NearestEalapsedTime, NearestErr
}
func ping_mongodb(c *gin.Context) {
primaryChan := make(chan time.Duration)
nearestChan := make(chan time.Duration)
errChan := make(chan error)

go func() {
PrimaryEalapsedTime, PrimaryErr := ping_mongodb_primary()
primaryChan <- PrimaryEalapsedTime
errChan <- PrimaryErr
}()

go func() {
NearestEalapsedTime, NearestErr := ping_mongodb_nearest()
nearestChan <- NearestEalapsedTime
errChan <- NearestErr
}()

PrimaryEalapsedTime := <-primaryChan
NearestEalapsedTime := <-nearestChan
PrimaryErr := <-errChan
NearestErr := <-errChan

if PrimaryErr != nil || NearestErr != nil {
c.JSON(500, gin.H{
"message": "MongoDB is down?",
"PrimaryEalapsedTime": PrimaryEalapsedTime.Milliseconds(),
"NearestEalapsedTime": NearestEalapsedTime.Milliseconds(),
})
} else {
c.JSON(200, gin.H{
"message": "MongoDB is up",
"PrimaryEalapsedTime": PrimaryEalapsedTime.Milliseconds(),
"NearestEalapsedTime": NearestEalapsedTime.Milliseconds(),
})
}
}

0 comments on commit 0c0d7f1

Please sign in to comment.