[go: up one dir, main page]

Skip to content

Commit

Permalink
feat: add "/api/status/test"
Browse files Browse the repository at this point in the history
  • Loading branch information
Calcium-Ion committed Mar 4, 2024
1 parent 912f46f commit fe7f42f
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
16 changes: 16 additions & 0 deletions controller/misc.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,22 @@ import (
"github.com/gin-gonic/gin"
)

func TestStatus(c *gin.Context) {
err := model.PingDB()
if err != nil {
c.JSON(http.StatusServiceUnavailable, gin.H{
"success": false,
"message": "数据库连接失败",
})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "Server is running",
})
return
}

func GetStatus(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"success": true,
Expand Down
32 changes: 32 additions & 0 deletions model/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ import (
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"log"
"one-api/common"
"os"
"strings"
"sync"
"time"
)

Expand Down Expand Up @@ -148,3 +150,33 @@ func CloseDB() error {
err = sqlDB.Close()
return err
}

var (
lastPingTime time.Time
pingMutex sync.Mutex
)

func PingDB() error {
pingMutex.Lock()
defer pingMutex.Unlock()

if time.Since(lastPingTime) < time.Second*10 {
return nil
}

sqlDB, err := DB.DB()
if err != nil {
log.Printf("Error getting sql.DB from GORM: %v", err)
return err
}

err = sqlDB.Ping()
if err != nil {
log.Printf("Error pinging DB: %v", err)
return err
}

lastPingTime = time.Now()
common.SysLog("Database pinged successfully")
return nil
}
1 change: 1 addition & 0 deletions router/api-router.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ func SetApiRouter(router *gin.Engine) {
apiRouter.Use(middleware.GlobalAPIRateLimit())
{
apiRouter.GET("/status", controller.GetStatus)
apiRouter.GET("/status/test", middleware.AdminAuth(), controller.TestStatus)
apiRouter.GET("/notice", controller.GetNotice)
apiRouter.GET("/about", controller.GetAbout)
apiRouter.GET("/midjourney", controller.GetMidjourney)
Expand Down

0 comments on commit fe7f42f

Please sign in to comment.