61 lines
1.2 KiB
Go
61 lines
1.2 KiB
Go
package middlewares
|
|
|
|
import (
|
|
"fmt"
|
|
"github.com/gin-gonic/gin"
|
|
"hospital-admin-api/api/responses"
|
|
"hospital-admin-api/consts"
|
|
"hospital-admin-api/global"
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
)
|
|
|
|
// RequestApi 请求api处理
|
|
func RequestApi() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
// 获取用户id
|
|
userId := c.GetInt64("UserId")
|
|
if userId == 0 {
|
|
responses.Fail(c)
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
key := "request_" + fmt.Sprintf("%d", userId)
|
|
|
|
res, _ := global.Redis.Get(c, "request_api"+key).Result()
|
|
if res == "" {
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"message": "长时间未操作,重新登录",
|
|
"code": consts.TokenExptired,
|
|
"data": "",
|
|
})
|
|
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
timestamp, err := strconv.ParseInt(res, 10, 64)
|
|
if err != nil {
|
|
fmt.Println("时间戳转换错误:", err)
|
|
return
|
|
}
|
|
|
|
now := time.Now().Unix() // 当前时间戳
|
|
diff := now - timestamp // 计算时间差(秒)
|
|
|
|
// 20-30分钟时,重新缓存
|
|
if diff >= 25*60 && diff <= 30*60 {
|
|
// 增加缓存
|
|
_, err := global.Redis.Set(c, "request_api"+key, time.Now().Unix(), 30*60*time.Second).Result()
|
|
if err != nil {
|
|
responses.FailWithMessage("错误", c)
|
|
return
|
|
}
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|