lolly/internal/server/server.go
xfy 413e418b37 test: 添加 handler/logging/middleware/server 模块单元测试
- internal/handler/static_test.go: 21 个测试用例覆盖静态文件服务和路径遍历安全
- internal/handler/router_test.go: 9 个测试用例覆盖路由注册和方法区分
- internal/logging/logging_test.go: 7 个测试用例覆盖日志级别解析
- internal/middleware/middleware_test.go: 4 个测试用例覆盖中间件链逆序包装
- internal/server/server_test.go: 5 个测试用例覆盖服务器创建和停止
- internal/server/vhost_test.go: 18 个测试用例覆盖虚拟主机路由

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 16:21:49 +08:00

76 lines
1.6 KiB
Go

package server
import (
"time"
"github.com/valyala/fasthttp"
"rua.plus/lolly/internal/config"
"rua.plus/lolly/internal/handler"
"rua.plus/lolly/internal/logging"
"rua.plus/lolly/internal/middleware"
)
// Server HTTP 服务器
type Server struct {
config *config.Config
fastServer *fasthttp.Server
handler fasthttp.RequestHandler
running bool
}
// New 创建服务器
func New(cfg *config.Config) *Server {
return &Server{config: cfg}
}
// Start 启动服务器
func (s *Server) Start() error {
// 初始化日志
logging.Init(s.config.Logging.Error.Level, true)
// 创建路由
router := handler.NewRouter()
// 静态文件服务
staticHandler := handler.NewStaticHandler(
s.config.Server.Static.Root,
s.config.Server.Static.Index,
)
// 注册路由 - 处理所有路径
router.GET("/{filepath:*}", staticHandler.Handle)
router.HEAD("/{filepath:*}", staticHandler.Handle)
// 应用中间件
chain := middleware.NewChain()
s.handler = chain.Apply(router.Handler())
// 创建 fasthttp 服务器
s.fastServer = &fasthttp.Server{
Name: "lolly",
Handler: s.handler,
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 120 * time.Second,
MaxConnsPerIP: 1000,
MaxRequestsPerConn: 10000,
}
s.running = true
return s.fastServer.ListenAndServe(s.config.Server.Listen)
}
// Stop 快速停止服务器
func (s *Server) Stop() error {
s.running = false
if s.fastServer != nil {
return s.fastServer.Shutdown()
}
return nil
}
// GracefulStop 优雅停止
func (s *Server) GracefulStop(timeout time.Duration) error {
return s.Stop()
}