feat: 前端搭建-未完成

This commit is contained in:
tbphp
2025-06-29 21:59:32 +08:00
parent ab95af0bbe
commit 731315144e
62 changed files with 4831 additions and 604 deletions

View File

@@ -0,0 +1,62 @@
package handler
import (
"net/http"
"github.com/gin-gonic/gin"
"gpt-load/internal/db"
"gpt-load/internal/models"
"gpt-load/internal/response"
)
// GetDashboardStats godoc
// @Summary Get dashboard statistics
// @Description Get statistics for the dashboard, including total requests, success rate, and group distribution.
// @Tags Dashboard
// @Accept json
// @Produce json
// @Success 200 {object} models.DashboardStats
// @Router /api/dashboard/stats [get]
func GetDashboardStats(c *gin.Context) {
var totalRequests, successRequests int64
var groupStats []models.GroupRequestStat
// Get total requests
if err := db.DB.Model(&models.RequestLog{}).Count(&totalRequests).Error; err != nil {
response.Error(c, http.StatusInternalServerError, "Failed to get total requests")
return
}
// Get success requests (status code 2xx)
if err := db.DB.Model(&models.RequestLog{}).Where("status_code >= ? AND status_code < ?", 200, 300).Count(&successRequests).Error; err != nil {
response.Error(c, http.StatusInternalServerError, "Failed to get success requests")
return
}
// Calculate success rate
var successRate float64
if totalRequests > 0 {
successRate = float64(successRequests) / float64(totalRequests)
}
// Get group stats
err := db.DB.Table("request_logs").
Select("groups.name as group_name, count(request_logs.id) as request_count").
Joins("join groups on groups.id = request_logs.group_id").
Group("groups.name").
Order("request_count desc").
Scan(&groupStats).Error
if err != nil {
response.Error(c, http.StatusInternalServerError, "Failed to get group stats")
return
}
stats := models.DashboardStats{
TotalRequests: totalRequests,
SuccessRequests: successRequests,
SuccessRate: successRate,
GroupStats: groupStats,
}
response.Success(c, stats)
}

View File

@@ -0,0 +1,125 @@
// Package handler provides HTTP handlers for the application
package handler
import (
"gpt-load/internal/models"
"gpt-load/internal/response"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
)
// CreateGroup handles the creation of a new group.
func (s *Server) CreateGroup(c *gin.Context) {
var group models.Group
if err := c.ShouldBindJSON(&group); err != nil {
response.Error(c, http.StatusBadRequest, "Invalid request body")
return
}
if err := s.DB.Create(&group).Error; err != nil {
response.Error(c, http.StatusInternalServerError, "Failed to create group")
return
}
response.Success(c, group)
}
// ListGroups handles listing all groups.
func (s *Server) ListGroups(c *gin.Context) {
var groups []models.Group
if err := s.DB.Find(&groups).Error; err != nil {
response.Error(c, http.StatusInternalServerError, "Failed to list groups")
return
}
response.Success(c, groups)
}
// GetGroup handles getting a single group by its ID.
func (s *Server) GetGroup(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
response.Error(c, http.StatusBadRequest, "Invalid group ID")
return
}
var group models.Group
if err := s.DB.Preload("APIKeys").First(&group, id).Error; err != nil {
response.Error(c, http.StatusNotFound, "Group not found")
return
}
response.Success(c, group)
}
// UpdateGroup handles updating an existing group.
func (s *Server) UpdateGroup(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
response.Error(c, http.StatusBadRequest, "Invalid group ID")
return
}
var group models.Group
if err := s.DB.First(&group, id).Error; err != nil {
response.Error(c, http.StatusNotFound, "Group not found")
return
}
var updateData models.Group
if err := c.ShouldBindJSON(&updateData); err != nil {
response.Error(c, http.StatusBadRequest, "Invalid request body")
return
}
// We only allow updating certain fields
group.Name = updateData.Name
group.Description = updateData.Description
group.ChannelType = updateData.ChannelType
group.Config = updateData.Config
if err := s.DB.Save(&group).Error; err != nil {
response.Error(c, http.StatusInternalServerError, "Failed to update group")
return
}
response.Success(c, group)
}
// DeleteGroup handles deleting a group.
func (s *Server) DeleteGroup(c *gin.Context) {
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
response.Error(c, http.StatusBadRequest, "Invalid group ID")
return
}
// Use a transaction to ensure atomicity
tx := s.DB.Begin()
if tx.Error != nil {
response.Error(c, http.StatusInternalServerError, "Failed to start transaction")
return
}
// Also delete associated API keys
if err := tx.Where("group_id = ?", id).Delete(&models.APIKey{}).Error; err != nil {
tx.Rollback()
response.Error(c, http.StatusInternalServerError, "Failed to delete associated API keys")
return
}
if err := tx.Delete(&models.Group{}, id).Error; err != nil {
tx.Rollback()
response.Error(c, http.StatusInternalServerError, "Failed to delete group")
return
}
if err := tx.Commit().Error; err != nil {
tx.Rollback()
response.Error(c, http.StatusInternalServerError, "Failed to commit transaction")
return
}
response.Success(c, gin.H{"message": "Group and associated keys deleted successfully"})
}

View File

@@ -6,35 +6,80 @@ import (
"runtime"
"time"
"gpt-load/internal/models"
"gpt-load/internal/types"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"gorm.io/gorm"
)
// Handler contains dependencies for HTTP handlers
type Handler struct {
keyManager types.KeyManager
config types.ConfigManager
// Server contains dependencies for HTTP handlers
type Server struct {
DB *gorm.DB
config types.ConfigManager
}
// NewHandler creates a new handler instance
func NewHandler(keyManager types.KeyManager, config types.ConfigManager) *Handler {
return &Handler{
keyManager: keyManager,
config: config,
// NewServer creates a new handler instance
func NewServer(db *gorm.DB, config types.ConfigManager) *Server {
return &Server{
DB: db,
config: config,
}
}
// RegisterAPIRoutes registers all API routes under a given router group
func (s *Server) RegisterAPIRoutes(api *gin.RouterGroup) {
// Group management routes
groups := api.Group("/groups")
{
groups.POST("", s.CreateGroup)
groups.GET("", s.ListGroups)
groups.GET("/:id", s.GetGroup)
groups.PUT("/:id", s.UpdateGroup)
groups.DELETE("/:id", s.DeleteGroup)
// Key management routes within a group
keys := groups.Group("/:id/keys")
{
keys.POST("", s.CreateKeysInGroup)
keys.GET("", s.ListKeysInGroup)
}
}
// Key management routes
api.PUT("/keys/:key_id", s.UpdateKey)
api.DELETE("/keys", s.DeleteKeys)
// Dashboard and logs routes
dashboard := api.Group("/dashboard")
{
dashboard.GET("/stats", GetDashboardStats)
}
api.GET("/logs", GetLogs)
// Settings routes
settings := api.Group("/settings")
{
settings.GET("", GetSettings)
settings.PUT("", UpdateSettings)
}
// Reload route
api.POST("/reload", s.ReloadConfig)
}
// Health handles health check requests
func (h *Handler) Health(c *gin.Context) {
stats := h.keyManager.GetStats()
func (s *Server) Health(c *gin.Context) {
var totalKeys, healthyKeys int64
s.DB.Model(&models.APIKey{}).Count(&totalKeys)
s.DB.Model(&models.APIKey{}).Where("status = ?", "active").Count(&healthyKeys)
status := "healthy"
httpStatus := http.StatusOK
// Check if there are any healthy keys
if stats.HealthyKeys == 0 {
if healthyKeys == 0 && totalKeys > 0 {
status = "unhealthy"
httpStatus = http.StatusServiceUnavailable
}
@@ -50,15 +95,23 @@ func (h *Handler) Health(c *gin.Context) {
c.JSON(httpStatus, gin.H{
"status": status,
"timestamp": time.Now().UTC().Format(time.RFC3339),
"healthy_keys": stats.HealthyKeys,
"total_keys": stats.TotalKeys,
"healthy_keys": healthyKeys,
"total_keys": totalKeys,
"uptime": uptime,
})
}
// Stats handles statistics requests
func (h *Handler) Stats(c *gin.Context) {
stats := h.keyManager.GetStats()
func (s *Server) Stats(c *gin.Context) {
var totalKeys, healthyKeys, disabledKeys int64
s.DB.Model(&models.APIKey{}).Count(&totalKeys)
s.DB.Model(&models.APIKey{}).Where("status = ?", "active").Count(&healthyKeys)
s.DB.Model(&models.APIKey{}).Where("status != ?", "active").Count(&disabledKeys)
// TODO: Get request counts from the database
var successCount, failureCount int64
s.DB.Model(&models.RequestLog{}).Where("status_code = ?", http.StatusOK).Count(&successCount)
s.DB.Model(&models.RequestLog{}).Where("status_code != ?", http.StatusOK).Count(&failureCount)
// Add additional system information
var m runtime.MemStats
@@ -66,15 +119,14 @@ func (h *Handler) Stats(c *gin.Context) {
response := gin.H{
"keys": gin.H{
"total": stats.TotalKeys,
"healthy": stats.HealthyKeys,
"blacklisted": stats.BlacklistedKeys,
"current_index": stats.CurrentIndex,
"total": totalKeys,
"healthy": healthyKeys,
"disabled": disabledKeys,
},
"requests": gin.H{
"success_count": stats.SuccessCount,
"failure_count": stats.FailureCount,
"total_count": stats.SuccessCount + stats.FailureCount,
"success_count": successCount,
"failure_count": failureCount,
"total_count": successCount + failureCount,
},
"memory": gin.H{
"alloc_mb": bToMb(m.Alloc),
@@ -95,48 +147,9 @@ func (h *Handler) Stats(c *gin.Context) {
c.JSON(http.StatusOK, response)
}
// Blacklist handles blacklist requests
func (h *Handler) Blacklist(c *gin.Context) {
blacklist := h.keyManager.GetBlacklist()
response := gin.H{
"blacklisted_keys": blacklist,
"count": len(blacklist),
"timestamp": time.Now().UTC().Format(time.RFC3339),
}
c.JSON(http.StatusOK, response)
}
// ResetKeys handles key reset requests
func (h *Handler) ResetKeys(c *gin.Context) {
// Reset blacklist
h.keyManager.ResetBlacklist()
// Reload keys from file
if err := h.keyManager.LoadKeys(); err != nil {
logrus.Errorf("Failed to reload keys: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Failed to reload keys",
"message": err.Error(),
})
return
}
stats := h.keyManager.GetStats()
c.JSON(http.StatusOK, gin.H{
"message": "Keys reset and reloaded successfully",
"total_keys": stats.TotalKeys,
"healthy_keys": stats.HealthyKeys,
"timestamp": time.Now().UTC().Format(time.RFC3339),
})
logrus.Info("Keys reset and reloaded successfully")
}
// MethodNotAllowed handles 405 requests
func (h *Handler) MethodNotAllowed(c *gin.Context) {
func (s *Server) MethodNotAllowed(c *gin.Context) {
c.JSON(http.StatusMethodNotAllowed, gin.H{
"error": "Method not allowed",
"path": c.Request.URL.Path,
@@ -146,7 +159,7 @@ func (h *Handler) MethodNotAllowed(c *gin.Context) {
}
// GetConfig returns configuration information (for debugging)
func (h *Handler) GetConfig(c *gin.Context) {
func (s *Server) GetConfig(c *gin.Context) {
// Only allow in development mode or with special header
if c.GetHeader("X-Debug-Config") != "true" {
c.JSON(http.StatusForbidden, gin.H{
@@ -155,13 +168,13 @@ func (h *Handler) GetConfig(c *gin.Context) {
return
}
serverConfig := h.config.GetServerConfig()
keysConfig := h.config.GetKeysConfig()
openaiConfig := h.config.GetOpenAIConfig()
authConfig := h.config.GetAuthConfig()
corsConfig := h.config.GetCORSConfig()
perfConfig := h.config.GetPerformanceConfig()
logConfig := h.config.GetLogConfig()
serverConfig := s.config.GetServerConfig()
keysConfig := s.config.GetKeysConfig()
openaiConfig := s.config.GetOpenAIConfig()
authConfig := s.config.GetAuthConfig()
corsConfig := s.config.GetCORSConfig()
perfConfig := s.config.GetPerformanceConfig()
logConfig := s.config.GetLogConfig()
// Sanitize sensitive information
sanitizedConfig := gin.H{

View File

@@ -0,0 +1,119 @@
// Package handler provides HTTP handlers for the application
package handler
import (
"gpt-load/internal/models"
"gpt-load/internal/response"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
)
type CreateKeysRequest struct {
Keys []string `json:"keys" binding:"required"`
}
// CreateKeysInGroup handles creating new keys within a specific group.
func (s *Server) CreateKeysInGroup(c *gin.Context) {
groupID, err := strconv.Atoi(c.Param("id"))
if err != nil {
response.Error(c, http.StatusBadRequest, "Invalid group ID")
return
}
var req CreateKeysRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.Error(c, http.StatusBadRequest, "Invalid request body")
return
}
var newKeys []models.APIKey
for _, keyVal := range req.Keys {
newKeys = append(newKeys, models.APIKey{
GroupID: uint(groupID),
KeyValue: keyVal,
Status: "active",
})
}
if err := s.DB.Create(&newKeys).Error; err != nil {
response.Error(c, http.StatusInternalServerError, "Failed to create keys")
return
}
response.Success(c, newKeys)
}
// ListKeysInGroup handles listing all keys within a specific group.
func (s *Server) ListKeysInGroup(c *gin.Context) {
groupID, err := strconv.Atoi(c.Param("id"))
if err != nil {
response.Error(c, http.StatusBadRequest, "Invalid group ID")
return
}
var keys []models.APIKey
if err := s.DB.Where("group_id = ?", groupID).Find(&keys).Error; err != nil {
response.Error(c, http.StatusInternalServerError, "Failed to list keys")
return
}
response.Success(c, keys)
}
// UpdateKey handles updating a specific key.
func (s *Server) UpdateKey(c *gin.Context) {
keyID, err := strconv.Atoi(c.Param("key_id"))
if err != nil {
response.Error(c, http.StatusBadRequest, "Invalid key ID")
return
}
var key models.APIKey
if err := s.DB.First(&key, keyID).Error; err != nil {
response.Error(c, http.StatusNotFound, "Key not found")
return
}
var updateData struct {
Status string `json:"status"`
}
if err := c.ShouldBindJSON(&updateData); err != nil {
response.Error(c, http.StatusBadRequest, "Invalid request body")
return
}
key.Status = updateData.Status
if err := s.DB.Save(&key).Error; err != nil {
response.Error(c, http.StatusInternalServerError, "Failed to update key")
return
}
response.Success(c, key)
}
type DeleteKeysRequest struct {
KeyIDs []uint `json:"key_ids" binding:"required"`
}
// DeleteKeys handles deleting one or more keys.
func (s *Server) DeleteKeys(c *gin.Context) {
var req DeleteKeysRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.Error(c, http.StatusBadRequest, "Invalid request body")
return
}
if len(req.KeyIDs) == 0 {
response.Error(c, http.StatusBadRequest, "No key IDs provided")
return
}
if err := s.DB.Delete(&models.APIKey{}, req.KeyIDs).Error; err != nil {
response.Error(c, http.StatusInternalServerError, "Failed to delete keys")
return
}
response.Success(c, gin.H{"message": "Keys deleted successfully"})
}

View File

@@ -0,0 +1,79 @@
package handler
import (
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
"gpt-load/internal/db"
"gpt-load/internal/models"
"gpt-load/internal/response"
)
// GetLogs godoc
// @Summary Get request logs
// @Description Get request logs with pagination and filtering
// @Tags Logs
// @Accept json
// @Produce json
// @Param page query int false "Page number"
// @Param size query int false "Page size"
// @Param group_id query int false "Group ID"
// @Param start_time query string false "Start time (RFC3339)"
// @Param end_time query string false "End time (RFC3339)"
// @Param status_code query int false "Status code"
// @Success 200 {array} models.RequestLog
// @Router /api/logs [get]
func GetLogs(c *gin.Context) {
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
size, _ := strconv.Atoi(c.DefaultQuery("size", "10"))
offset := (page - 1) * size
query := db.DB.Model(&models.RequestLog{})
if groupIDStr := c.Query("group_id"); groupIDStr != "" {
groupID, err := strconv.Atoi(groupIDStr)
if err == nil {
query = query.Where("group_id = ?", groupID)
}
}
if startTimeStr := c.Query("start_time"); startTimeStr != "" {
startTime, err := time.Parse(time.RFC3339, startTimeStr)
if err == nil {
query = query.Where("timestamp >= ?", startTime)
}
}
if endTimeStr := c.Query("end_time"); endTimeStr != "" {
endTime, err := time.Parse(time.RFC3339, endTimeStr)
if err == nil {
query = query.Where("timestamp <= ?", endTime)
}
}
if statusCodeStr := c.Query("status_code"); statusCodeStr != "" {
statusCode, err := strconv.Atoi(statusCodeStr)
if err == nil {
query = query.Where("status_code = ?", statusCode)
}
}
var logs []models.RequestLog
var total int64
query.Count(&total)
err := query.Order("timestamp desc").Offset(offset).Limit(size).Find(&logs).Error
if err != nil {
response.Error(c, http.StatusInternalServerError, "Failed to get logs")
return
}
c.JSON(http.StatusOK, gin.H{
"total": total,
"page": page,
"size": size,
"data": logs,
})
}

View File

@@ -0,0 +1,26 @@
package handler
import (
"gpt-load/internal/response"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
)
// ReloadConfig handles the POST /api/reload request.
// It triggers a configuration reload.
func (s *Server) ReloadConfig(c *gin.Context) {
if s.config == nil {
response.InternalError(c, "Configuration manager is not initialized")
return
}
err := s.config.ReloadConfig()
if err != nil {
logrus.Errorf("Failed to reload config: %v", err)
response.InternalError(c, "Failed to reload config")
return
}
response.Success(c, gin.H{"message": "Configuration reloaded successfully"})
}

View File

@@ -0,0 +1,62 @@
package handler
import (
"gpt-load/internal/db"
"gpt-load/internal/models"
"gpt-load/internal/response"
"github.com/gin-gonic/gin"
"gorm.io/gorm/clause"
)
// GetSettings handles the GET /api/settings request.
// It retrieves all system settings from the database and returns them as a key-value map.
func GetSettings(c *gin.Context) {
var settings []models.SystemSetting
if err := db.DB.Find(&settings).Error; err != nil {
response.InternalError(c, "Failed to retrieve settings")
return
}
settingsMap := make(map[string]string)
for _, s := range settings {
settingsMap[s.SettingKey] = s.SettingValue
}
response.Success(c, settingsMap)
}
// UpdateSettings handles the PUT /api/settings request.
// It receives a key-value JSON object and updates or creates settings in the database.
func UpdateSettings(c *gin.Context) {
var settingsMap map[string]string
if err := c.ShouldBindJSON(&settingsMap); err != nil {
response.BadRequest(c, "Invalid request body")
return
}
var settingsToUpdate []models.SystemSetting
for key, value := range settingsMap {
settingsToUpdate = append(settingsToUpdate, models.SystemSetting{
SettingKey: key,
SettingValue: value,
})
}
if len(settingsToUpdate) == 0 {
response.Success(c, nil)
return
}
// Using OnConflict to perform an "upsert" operation.
// If a setting with the same key exists, it will be updated. Otherwise, a new one will be created.
if err := db.DB.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "setting_key"}},
DoUpdates: clause.AssignmentColumns([]string{"setting_value"}),
}).Create(&settingsToUpdate).Error; err != nil {
response.InternalError(c, "Failed to update settings")
return
}
response.Success(c, nil)
}