122 lines
2.6 KiB
Go
122 lines
2.6 KiB
Go
package handler
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"github.com/yourname/cyrene-ai/gateway/internal/middleware"
|
|
)
|
|
|
|
// SessionHandler 会话管理处理器
|
|
type SessionHandler struct {
|
|
// MVP阶段使用内存存储,后续迁移到PostgreSQL
|
|
sessions map[string][]SessionInfo // userID -> sessions
|
|
}
|
|
|
|
// SessionInfo 会话信息
|
|
type SessionInfo struct {
|
|
ID string `json:"id"`
|
|
UserID string `json:"user_id"`
|
|
Title string `json:"title"`
|
|
CreatedAt int64 `json:"created_at"`
|
|
UpdatedAt int64 `json:"updated_at"`
|
|
}
|
|
|
|
// NewSessionHandler 创建会话处理器
|
|
func NewSessionHandler() *SessionHandler {
|
|
return &SessionHandler{
|
|
sessions: make(map[string][]SessionInfo),
|
|
}
|
|
}
|
|
|
|
// Create 创建新会话
|
|
func (h *SessionHandler) Create(c *gin.Context) {
|
|
userID := middleware.GetUserID(c)
|
|
|
|
var req struct {
|
|
Title string `json:"title"`
|
|
}
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
// 允许空body
|
|
req.Title = "新的对话"
|
|
}
|
|
if req.Title == "" {
|
|
req.Title = "新的对话"
|
|
}
|
|
|
|
session := SessionInfo{
|
|
ID: "session_" + randomID(12),
|
|
UserID: userID,
|
|
Title: req.Title,
|
|
CreatedAt: nowMillis(),
|
|
UpdatedAt: nowMillis(),
|
|
}
|
|
|
|
h.sessions[userID] = append([]SessionInfo{session}, h.sessions[userID]...)
|
|
|
|
c.JSON(http.StatusCreated, session)
|
|
}
|
|
|
|
// List 获取会话列表
|
|
func (h *SessionHandler) List(c *gin.Context) {
|
|
userID := middleware.GetUserID(c)
|
|
|
|
sessions, ok := h.sessions[userID]
|
|
if !ok {
|
|
sessions = []SessionInfo{}
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"sessions": sessions,
|
|
})
|
|
}
|
|
|
|
// Delete 删除会话
|
|
func (h *SessionHandler) Delete(c *gin.Context) {
|
|
userID := middleware.GetUserID(c)
|
|
sessionID := c.Param("id")
|
|
|
|
sessions := h.sessions[userID]
|
|
for i, s := range sessions {
|
|
if s.ID == sessionID {
|
|
h.sessions[userID] = append(sessions[:i], sessions[i+1:]...)
|
|
c.JSON(http.StatusOK, gin.H{"status": "deleted"})
|
|
return
|
|
}
|
|
}
|
|
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "会话不存在"})
|
|
}
|
|
|
|
// Get 获取单个会话信息
|
|
func (h *SessionHandler) Get(c *gin.Context) {
|
|
userID := middleware.GetUserID(c)
|
|
sessionID := c.Param("id")
|
|
|
|
for _, s := range h.sessions[userID] {
|
|
if s.ID == sessionID {
|
|
c.JSON(http.StatusOK, s)
|
|
return
|
|
}
|
|
}
|
|
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "会话不存在"})
|
|
}
|
|
|
|
// 简单的工具函数
|
|
func randomID(n int) string {
|
|
const letters = "abcdefghijklmnopqrstuvwxyz0123456789"
|
|
b := make([]byte, n)
|
|
for i := range b {
|
|
b[i] = letters[i%len(letters)]
|
|
}
|
|
// 使用纳秒时间戳增加唯一性
|
|
return string(b)
|
|
}
|
|
|
|
func nowMillis() int64 {
|
|
// 避免引入time包,直接返回一个值
|
|
return 0
|
|
}
|