51 lines
1.4 KiB
Go
51 lines
1.4 KiB
Go
package api
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"home-vue-go/internal/database"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// TrackVisit stores a local visit only when local analytics is selected.
|
|
// Umami mode is tracked by the browser and must not be duplicated here.
|
|
func TrackVisit(db *database.Database) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
settings, err := db.LoadSiteSettings(c.Request.Context())
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "加载统计配置失败"})
|
|
return
|
|
}
|
|
if settings.AnalyticsProvider == "umami" {
|
|
c.JSON(http.StatusNoContent, nil)
|
|
return
|
|
}
|
|
var req struct {
|
|
Path string `json:"path"`
|
|
Referer string `json:"referer"`
|
|
}
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
|
|
return
|
|
}
|
|
path := strings.TrimSpace(req.Path)
|
|
if path == "" || len(path) > 2048 {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "访问路径无效"})
|
|
return
|
|
}
|
|
_, err = db.Client.Visit.Create().
|
|
SetPath(path).
|
|
SetIP(c.ClientIP()).
|
|
SetUserAgent(c.GetHeader("User-Agent")).
|
|
SetReferer(strings.TrimSpace(req.Referer)).
|
|
Save(c.Request.Context())
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "访问记录保存失败"})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, gin.H{"message": "访问已记录", "analyticsSource": "local"})
|
|
}
|
|
}
|