63 lines
1.4 KiB
Go
63 lines
1.4 KiB
Go
package server
|
|
|
|
import (
|
|
"fmt"
|
|
"net"
|
|
"net/http"
|
|
"os"
|
|
|
|
"aichat/config"
|
|
"aichat/conversation"
|
|
"aichat/llm"
|
|
"aichat/toolmanager"
|
|
"aichat/toolrouter"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type Server struct {
|
|
cfg *config.Config
|
|
aiState *llm.State
|
|
toolManager *toolmanager.Manager
|
|
toolRouterState *toolrouter.State
|
|
store *conversation.Store
|
|
router *gin.Engine
|
|
}
|
|
|
|
func New(cfg *config.Config, aiState *llm.State, toolManager *toolmanager.Manager, toolRouterState *toolrouter.State, store *conversation.Store) *Server {
|
|
s := &Server{
|
|
cfg: cfg,
|
|
aiState: aiState,
|
|
toolManager: toolManager,
|
|
toolRouterState: toolRouterState,
|
|
store: store,
|
|
router: gin.Default(),
|
|
}
|
|
s.router.LoadHTMLGlob("templates/*")
|
|
s.router.Static("/static", "./static")
|
|
s.registerRoutes()
|
|
return s
|
|
}
|
|
|
|
func (s *Server) Run() error {
|
|
switch s.cfg.Server.Mode {
|
|
case "unix":
|
|
return s.runUnix(s.cfg.Server.Address)
|
|
default:
|
|
fmt.Println("服务已启动,监听 TCP:", s.cfg.Server.Address)
|
|
return s.router.Run(s.cfg.Server.Address)
|
|
}
|
|
}
|
|
|
|
func (s *Server) runUnix(socketPath string) error {
|
|
if _, statErr := os.Stat(socketPath); statErr == nil {
|
|
os.Remove(socketPath)
|
|
}
|
|
ln, err := net.Listen("unix", socketPath)
|
|
if err != nil {
|
|
return fmt.Errorf("监听 Unix socket 失败: %w", err)
|
|
}
|
|
fmt.Println("服务已启动,监听 Unix socket:", socketPath)
|
|
return http.Serve(ln, s.router)
|
|
}
|