lolly/internal/server/vhost.go
xfy 616762e840 refactor(netutil): 提取通用主机名处理函数
- 新增 StripPort() 函数用于移除主机名中的端口
- 新增 HasPort() 函数用于检测主机名是否包含端口
- 替代 vhost 和 ssl 模块中的内联端口处理逻辑

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-10 11:20:10 +08:00

97 lines
2.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Package server 提供 HTTP 服务器的核心实现,支持单服务器和虚拟主机两种运行模式。
//
// 该文件包含虚拟主机管理相关的核心逻辑,包括:
// - 虚拟主机管理器的创建和配置
// - 基于 Host 头的请求分发
// - 默认主机 fallback 机制
//
// 主要用途:
//
// 用于支持多域名虚拟主机场景,根据请求的 Host 头分发到不同的处理器。
//
// 注意事项:
// - 所有方法均为并发安全
// - 未匹配的 Host 头请求由默认主机处理
//
// 作者xfy
package server
import (
"github.com/valyala/fasthttp"
"rua.plus/lolly/internal/netutil"
)
// VHostManager 虚拟主机管理器。
//
// 管理多个虚拟主机,根据请求的 Host 头分发到对应的处理器。
// 支持默认主机作为未匹配请求的 fallback。
type VHostManager struct {
// hosts 虚拟主机映射,按 server name 索引
hosts map[string]*VirtualHost
// defaultHost 默认主机,处理未匹配的 Host 头请求
defaultHost *VirtualHost
}
// VirtualHost 虚拟主机。
//
// 代表一个虚拟主机配置,包含名称和对应的请求处理器。
type VirtualHost struct {
// name 虚拟主机名称(域名)
name string
// handler 请求处理器
handler fasthttp.RequestHandler
}
// NewVHostManager 创建虚拟主机管理器。
//
// 返回值:
// - *VHostManager: 新创建的管理器实例
func NewVHostManager() *VHostManager {
return &VHostManager{
hosts: make(map[string]*VirtualHost),
}
}
// AddHost 添加虚拟主机。
//
// 参数:
// - name: 虚拟主机名称(域名)
// - handler: 请求处理器
func (v *VHostManager) AddHost(name string, handler fasthttp.RequestHandler) {
v.hosts[name] = &VirtualHost{
name: name,
handler: handler,
}
}
// SetDefault 设置默认主机。
//
// 参数:
// - handler: 默认主机的请求处理器
func (v *VHostManager) SetDefault(handler fasthttp.RequestHandler) {
v.defaultHost = &VirtualHost{
name: "default",
handler: handler,
}
}
// Handler 返回虚拟主机选择器。
//
// 返回值:
// - fasthttp.RequestHandler: 根据 Host 头分发请求的处理器
func (v *VHostManager) Handler() fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
host := netutil.StripPort(string(ctx.Host()))
if vhost, ok := v.hosts[host]; ok {
vhost.handler(ctx)
} else if v.defaultHost != nil {
v.defaultHost.handler(ctx)
} else {
ctx.Error("Host not found", fasthttp.StatusNotFound)
}
}
}