types

package
v3.3.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 20, 2026 License: BSD-3-Clause Imports: 6 Imported by: 0

Documentation

Index

Constants

View Source
const (
	AlgoRoundRobin = ""           // 轮询
	AlgoLeastConn  = "least_conn" // 最少连接
	AlgoIPHash     = "ip_hash"    // 按客户端 IP
	AlgoRandom     = "random"     // 随机
)

负载均衡算法的规范值,取 nginx 写法。各方言写入时映射到自己的语法, 没有对应实现的降级为轮询并把原值留在注释里,换服务器时不丢

Variables

View Source
var ApacheVars = NewVarMap([][2]string{
	{"$proxy_add_x_forwarded_for", "%{HTTP:X-Forwarded-For}"},
	{"$remote_addr", "%{REMOTE_ADDR}"},
	{"$host", "%{HTTP_HOST}"},
	{"$http_host", "%{HTTP_HOST}"},
	{"$request_uri", "%{REQUEST_URI}"},
	{"$server_name", "%{SERVER_NAME}"},
	{"$server_port", "%{SERVER_PORT}"},
	{"$scheme", "%{REQUEST_SCHEME}"},
})

ApacheVars nginx 变量到 Apache 表达式的映射。表首命中即回读时的规范原像,所以 $host 要排在 $http_host 之前。 OpenLiteSpeed 的 extraHeaders 用的也是 Apache 指令语法,两者共用

Functions

func NormalizeAlgo added in v3.3.6

func NormalizeAlgo(algo string) string

NormalizeAlgo 收敛到规范算法名,无法识别的按轮询处理

func NormalizePath added in v3.3.6

func NormalizePath(path string) string

func WriteUserFile added in v3.3.6

func WriteUserFile(userFile, suffix, sep string) (bool, error)

WriteUserFile 把面板的明文 htpasswd 转写成方言能用的加密文件,返回里面是否有用户。 面板文件保持 {PLAIN} 明文以便回读,而 Apache 在 Unix 下不认明文密码、Caddy 只收 bcrypt 或 argon2id; 用户文件缺失时当作没有用户,不能阻塞整个站点保存

Types

type AccessControlConfig

type AccessControlConfig struct {
	// 允许的 IP/CIDR 列表 (allow)
	Allow []string `form:"allow" json:"allow"`

	// 拒绝的 IP/CIDR 列表 (deny)
	Deny []string `form:"deny" json:"deny"`
}

type BasicAuth added in v3.3.4

type BasicAuth struct {
	Path     string `json:"path"`      // 生效路径前缀,"/" 表示整站
	UserFile string `json:"user_file"` // htpasswd 文件路径
}

type CacheConfig

type CacheConfig struct {
	// 缓存时长,状态码 -> 时长,如: {"200 302": "10m", "404": "1m", "any": "5m"}
	Valid map[string]string `form:"valid" json:"valid"`

	// 不缓存条件 (proxy_cache_bypass + proxy_no_cache)
	// 常用值: "$cookie_nocache", "$arg_nocache", "$http_pragma", "$http_authorization"
	NoCacheConditions []string `form:"no_cache_conditions" json:"no_cache_conditions"`

	// 过期缓存使用策略 (proxy_cache_use_stale)
	// 可选值: "error", "timeout", "updating", "http_500", "http_502", "http_503", "http_504"
	UseStale []string `form:"use_stale" json:"use_stale"`

	// 后台更新 (proxy_cache_background_update)
	BackgroundUpdate bool `form:"background_update" json:"background_update"`

	// 缓存锁 (proxy_cache_lock),防止缓存击穿
	Lock bool `form:"lock" json:"lock"`

	// 最小请求次数 (proxy_cache_min_uses),请求 N 次后才缓存
	MinUses int `form:"min_uses" json:"min_uses"`

	// 缓存方法 (proxy_cache_methods),默认 GET HEAD
	Methods []string `form:"methods" json:"methods"`

	// 自定义缓存键 (proxy_cache_key)
	Key string `form:"key" json:"key"`
}

type ConfigScope added in v3.2.5

type ConfigScope string
const (
	ScopeSite   ConfigScope = "site"   // 站点级片段(site/ 目录)
	ScopeShared ConfigScope = "shared" // 共享级片段(shared/ 目录)
)

type Dialect added in v3.3.6

type Dialect interface {
	Service() string
	ConfigTest() string
	// HTMLDir 默认页目录,存放 index.html、stop.html 与 404.html
	HTMLDir() string
	ConfigFile() string
	PanelACMEConf() string
	Features() Features
	HTTPSListenArgs() []string
	ErrorPageConf() string
	PHPCacheConf() string
	SPAConf() string
	// LSCacheConf 站点级 LiteSpeed 页面缓存片段,name 为站点名
	LSCacheConf(name string) string
	// StatConf 访问统计片段,shared 为共享级、site 为站点级,不支持统计时都为空
	StatConf(name string) (shared, site string)
	// DefaultSiteConf 内置默认站点的独立配置文件,没有时为空
	DefaultSiteConf() string
	// WriteDefaultSite 写入内置默认站点配置,asDefault 为 false 时把默认位让给某个站点
	WriteDefaultSite(asDefault bool) error
	HTPasswdLine(username, password string) string
	// RewritesDir 伪静态预置目录名,语法相同的服务器可共用
	RewritesDir() string
	// BeforeReload 重载前的准备工作,如重建全局配置
	BeforeReload() error

	NewStaticVhost(configDir string) (StaticVhost, error)
	NewPHPVhost(configDir string) (PHPVhost, error)
	NewProxyVhost(configDir string) (ProxyVhost, error)

	// 以下方法的 bool 返回值表示配置是否变化,未变化则跳过重载
	// WriteSiteChallenge 向网站 acme 配置文件投放一个 HTTP-01 验证
	WriteSiteChallenge(conf, path, token string) (bool, error)
	// RemoveSiteChallenge 移除网站 acme 配置文件中的一个 HTTP-01 验证
	RemoveSiteChallenge(conf, path, token string) (bool, error)
	// WritePanelChallenge 写入面板独立验证站点,用于 80 端口已被 Web 服务器占用时签发面板证书
	WritePanelChallenge(conf string, names []string, tokens map[string]string) (bool, error)
	RemovePanelChallenge(conf string) (bool, error)
}

Dialect 收敛某种 Web 服务器在面板层面的全部差异,新增服务器只需实现此接口并在 webserver 包中注册

type Features added in v3.3.6

type Features struct {
	IPv6Listen  bool // 站点额外监听 IPv6 地址
	Stat        bool // 访问统计
	DefaultSite bool // 默认站点切换
	LSCache     bool // LiteSpeed 页面缓存
}

Features Web 服务器能力集,不支持的功能由调用方按需降级

type IncludeFile

type IncludeFile struct {
	Path    string   `json:"path"`    // 文件路径
	Comment []string `json:"comment"` // 注释说明
}

type Listen

type Listen struct {
	Address string   `form:"address" json:"address"` // 监听地址,如: "80", "0.0.0.0:80", "[::]:443"
	Args    []string `form:"args" json:"args"`       // 其他参数,如: ["default_server", "ssl", "quic"]
}

type LocationKind added in v3.3.6

type LocationKind uint8

LocationKind location 的匹配方式,面板统一用 nginx 的写法表达,各方言自行渲染

const (
	LocationPrefix   LocationKind = iota // 前缀匹配,含 ^~
	LocationExact                        // = 精确匹配
	LocationRegex                        // ~ 正则
	LocationRegexAny                     // ~* 正则,不区分大小写
)

func ParseLocation added in v3.3.6

func ParseLocation(location string) (LocationKind, string)

ParseLocation 拆出匹配方式与其后的路径或正则。nginx 允许操作符与后串之间没有空格

type PHPVhost

type PHPVhost interface {
	Vhost
	VhostPHP
	VhostRedirect
}

type Proxy

type Proxy struct {
	Location          string                `form:"location" json:"location" validate:"required"`             // 匹配路径,如: "/", "/api", "~ ^/api/v[0-9]+/"
	Pass              string                `form:"pass" json:"pass" validate:"required"`                     // 代理地址,如: "http://example.com", "http://backend"
	Host              string                `form:"host" json:"host"`                                         // 代理 Host,如: "example.com"
	SNI               string                `form:"sni" json:"sni"`                                           // 代理 SNI,如: "example.com"
	Cache             *CacheConfig          `form:"cache" json:"cache"`                                       // 缓存配置,nil 表示禁用缓存
	Buffering         bool                  `form:"buffering" json:"buffering"`                               // 是否启用缓冲
	Resolver          []string              `form:"resolver" json:"resolver"`                                 // 自定义 DNS 解析器配置,如: ["8.8.8.8", "ipv6=off"]
	ResolverTimeout   time.Duration         `form:"resolver_timeout" json:"resolver_timeout"`                 // DNS 解析超时时间,如: 5 * time.Second
	Headers           map[string]string     `form:"headers" json:"headers"`                                   // 自定义请求头,如: map["X-Custom-Header"] = "value"
	Replaces          map[string]string     `form:"replaces" json:"replaces"`                                 // 响应内容替换,如: map["/old"] = "/new"
	HTTPVersion       string                `form:"http_version" json:"http_version" validate:"in:1.0,1.1,2"` // HTTP 协议版本 (proxy_http_version),可选: "1.0", "1.1", "2"
	Timeout           *TimeoutConfig        `form:"timeout" json:"timeout"`                                   // 超时配置
	Retry             *RetryConfig          `form:"retry" json:"retry"`                                       // 重试配置
	ClientMaxBodySize int64                 `form:"client_max_body_size" json:"client_max_body_size"`         // 请求体大小限制 (client_max_body_size),单位字节,0 表示使用全局配置
	SSLBackend        *SSLBackendConfig     `form:"ssl_backend" json:"ssl_backend"`                           // SSL 后端验证配置
	ResponseHeaders   *ResponseHeaderConfig `form:"response_headers" json:"response_headers"`                 // 响应头修改配置
	AccessControl     *AccessControlConfig  `form:"access_control" json:"access_control"`                     // IP 访问控制配置
}

type ProxyVhost

type ProxyVhost interface {
	Vhost
	VhostRedirect
	VhostProxy
}

type RateLimit

type RateLimit struct {
	PerServer int `json:"per_server"` // 站点最大并发数 (limit_conn perserver X)
	PerIP     int `json:"per_ip"`     // 单 IP 最大并发数 (limit_conn perip X)
	Rate      int `json:"rate"`       // 流量限制,单位 KB (limit_rate Xk)
}

type RealIP

type RealIP struct {
	From      []string `json:"from"`      // 可信 IP 来源列表 (set_real_ip_from)
	Header    string   `json:"header"`    // 真实 IP 头 (real_ip_header),如: X-Real-IP, X-Forwarded-For
	Recursive bool     `json:"recursive"` // 递归搜索 (real_ip_recursive)
}

type Redirect

type Redirect struct {
	Type       RedirectType `json:"type"`        // 重定向类型
	From       string       `json:"from"`        // 源地址,如: "example.com", "http://example.com", "/old"
	To         string       `json:"to"`          // 目标地址,如: "https://example.com"
	KeepURI    bool         `json:"keep_uri"`    // 是否保持 URI 不变(即保留请求参数)
	StatusCode int          `json:"status_code"` // 自定义状态码,如: 301, 302, 307, 308,默认 308
}

type RedirectType

type RedirectType string
const (
	RedirectType404  RedirectType = "404"  // 404 重定向
	RedirectTypeHost RedirectType = "host" // 主机名重定向
	RedirectTypeURL  RedirectType = "url"  // URL 重定向
)

type ResponseHeaderConfig

type ResponseHeaderConfig struct {
	// 隐藏的响应头 (proxy_hide_header)
	Hide []string `form:"hide" json:"hide"`

	// 添加的响应头 (add_header),key -> value
	// 值可以包含变量,如 $upstream_cache_status
	Add map[string]string `form:"add" json:"add"`
}

type RetryConfig

type RetryConfig struct {
	// 触发重试的条件 (proxy_next_upstream)
	// 可选值: "error", "timeout", "invalid_header", "http_500", "http_502", "http_503", "http_504", "http_429", "non_idempotent", "off"
	Conditions []string `form:"conditions" json:"conditions"`

	// 最大重试次数 (proxy_next_upstream_tries),0 表示不限制
	Tries int `form:"tries" json:"tries"`

	// 重试超时时间 (proxy_next_upstream_timeout),0 表示不限制
	Timeout time.Duration `form:"timeout" json:"timeout"`
}

type SSLBackendConfig

type SSLBackendConfig struct {
	Verify             bool   `form:"verify" json:"verify"`                           // proxy_ssl_verify on/off
	TrustedCertificate string `form:"trusted_certificate" json:"trusted_certificate"` // proxy_ssl_trusted_certificate 路径
	VerifyDepth        int    `form:"verify_depth" json:"verify_depth"`               // proxy_ssl_verify_depth,默认 1
}

type SSLConfig

type SSLConfig struct {
	Cert      string   `json:"cert"`      // 证书路径
	Key       string   `json:"key"`       // 私钥路径
	Protocols []string `json:"protocols"` // 支持的协议,如: ["TLSv1.2", "TLSv1.3"]

	// 高级选项
	HSTS         bool   `json:"hsts"`          // HTTP 严格传输安全
	OCSP         bool   `json:"ocsp"`          // OCSP Stapling
	HTTPRedirect bool   `json:"http_redirect"` // HTTP 强制跳转 HTTPS
	AltSvc       string `json:"alt_svc"`       // Alt-Svc 配置,如: 'h3=":443"; ma=86400'
}

type StaticVhost

type StaticVhost interface {
	Vhost
	VhostRedirect
}

type TimeoutConfig

type TimeoutConfig struct {
	Connect time.Duration `form:"connect" json:"connect"` // proxy_connect_timeout,默认 60s
	Read    time.Duration `form:"read" json:"read"`       // proxy_read_timeout,默认 60s
	Send    time.Duration `form:"send" json:"send"`       // proxy_send_timeout,默认 60s
}

type Upstream

type Upstream struct {
	Name            string            `form:"name" json:"name" validate:"required"`       // 上游名称,如: "backend"
	Servers         map[string]string `form:"servers" json:"servers" validate:"required"` // 上游服务器及配置,如: map["server1"] = "weight=5 resolve"
	Algo            string            `form:"algo" json:"algo"`                           // 负载均衡算法,如: "least_conn", "ip_hash"
	Keepalive       int               `form:"keepalive" json:"keepalive"`                 // 保持连接数,如: 32
	Resolver        []string          `form:"resolver" json:"resolver"`                   // 自定义 DNS 解析器配置,如: ["8.8.8.8", "ipv6=off"]
	ResolverTimeout time.Duration     `form:"resolver_timeout" json:"resolver_timeout"`   // DNS 解析超时时间,如: 5 * time.Second
}

type VarMap added in v3.3.6

type VarMap struct {
	// contains filtered or unexported fields
}

VarMap nginx 变量与某个方言的占位符之间的双向映射。面板的头部值统一存 nginx 写法, 照搬到别的方言会被当字面量发给上游,所以写入时换成该方言的占位符、回读时换回来。 多个 nginx 变量映射到同一个占位符时,回读取表中首个,所以最常用的写法要排在前面

func NewVarMap added in v3.3.6

func NewVarMap(pairs [][2]string) *VarMap

func (*VarMap) ToNative added in v3.3.6

func (m *VarMap) ToNative(value string) string

func (*VarMap) ToNginx added in v3.3.6

func (m *VarMap) ToNginx(value string) string

type Vhost

type Vhost interface {
	Enable() bool
	SetEnable(enable bool) error

	// Default 是否为默认站点,承接未匹配任何域名的请求
	Default() bool
	SetDefault(enable bool) error

	Listen() []Listen
	SetListen(listen []Listen) error

	// ServerName 取服务器名称,如: ["example.com", "www.example.com"]
	ServerName() []string
	SetServerName(serverName []string) error

	// Index 取默认首页,如: ["index.php", "index.html"]
	Index() []string
	SetIndex(index []string) error

	// Root 取网站根目录,如: "/opt/ace/sites/example/public"
	Root() string
	SetRoot(root string) error

	Includes() []IncludeFile
	SetIncludes(includes []IncludeFile) error

	// AccessLog 取访问日志路径,如: "/opt/ace/sites/example/log/access.log"
	AccessLog() string
	SetAccessLog(accessLog string) error

	// ErrorLog 取错误日志路径,如: "/opt/ace/sites/example/log/error.log"
	ErrorLog() string
	SetErrorLog(errorLog string) error

	Save() error
	Reset() error

	SSL() bool
	SSLConfig() *SSLConfig
	SetSSLConfig(cfg *SSLConfig) error
	ClearSSL() error

	RateLimit() *RateLimit
	SetRateLimit(limit *RateLimit) error
	ClearRateLimit() error

	BasicAuth() []BasicAuth
	SetBasicAuth(auths []BasicAuth) error
	ClearBasicAuth() error

	RealIP() *RealIP
	SetRealIP(realIP *RealIP) error
	ClearRealIP() error

	Config(name string, scope ConfigScope) string
	// SetConfig 设置指定名称的配置内容,自动添加生成标记注释
	SetConfig(name string, scope ConfigScope, content string) error
	// SetRawConfig 设置配置内容但不添加生成标记注释(用于用户可编辑的片段)
	SetRawConfig(name string, scope ConfigScope, content string) error
	RemoveConfig(name string, scope ConfigScope) error
}

type VhostPHP

type VhostPHP interface {
	// PHP 取 PHP 版本,如: 84, 81, 80, 0 表示未启用 PHP
	PHP() uint
	SetPHP(version uint) error
}

type VhostProxy

type VhostProxy interface {
	Proxies() []Proxy
	SetProxies(proxies []Proxy) error
	ClearProxies() error

	Upstreams() []Upstream
	SetUpstreams(upstreams []Upstream) error
	ClearUpstreams() error
}

type VhostRedirect

type VhostRedirect interface {
	Redirects() []Redirect
	SetRedirects(redirects []Redirect) error
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL