webservice

package
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2026 License: Apache-2.0 Imports: 49 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package webservice 实现 Web 服务模块:按域名把请求分发到反向代理、重定向、静态文件或固定文本, 支持 HTTPS(证书来自证书模块)、PROXY 协议、基本认证、网页认证与 IP 访问控制。

Index

Constants

View Source
const (
	CountryOff   = ""
	CountryAllow = "allow"
	CountryDeny  = "deny"
)

国家过滤模式

View Source
const (
	RuleAuthInherit = ""
	RuleAuthOff     = "off"
	RuleAuthOn      = "on"
)

路径规则的认证覆盖

View Source
const (
	TypeProxy    = "proxy"
	TypeRedirect = "redirect"
	TypeStatic   = "static"
	TypeText     = "text"
)

站点类型

View Source
const (
	IPModeOff       = ""
	IPModeWhitelist = "whitelist"
	IPModeBlacklist = "blacklist"
)

访问控制模式

View Source
const (
	LBRoundRobin = ""
	LBRandom     = "random"
	LBIPHash     = "ip_hash"
	LBLeastConn  = "least_conn"
)

负载均衡策略

View Source
const ID = "webservice"

ID 是模块标识。

Variables

This section is empty.

Functions

This section is empty.

Types

type AuthUser added in v0.5.2

type AuthUser struct {
	Name string `json:"name"`
	// Password 保存 bcrypt 哈希;接口提交明文时自动哈希,读取时脱敏
	Password string `json:"password"`
	// TOTPSecret 为 Base32 密钥,留空表示不启用二次验证;读取时脱敏
	TOTPSecret string `json:"totpSecret"`
	Remark     string `json:"remark"`
}

AuthUser 是可在多个站点共用的认证用户。站点开启“使用共享用户”后,网页认证与基本认证都接受这些用户, 设置了 TOTP 的用户在网页登录时还需输入动态验证码(相当于 Authelia 的 two_factor 策略)。

type BanInfo added in v0.3.0

type BanInfo struct {
	// Key 为被封禁的地址(IPv6 按 /64 聚合)
	Key    string    `json:"key"`
	Until  time.Time `json:"until"`
	Reason string    `json:"reason"`
	Manual bool      `json:"manual"`
}

BanInfo 是封禁列表中的一项。

type CacheConfig added in v0.3.0

type CacheConfig struct {
	Enable bool `json:"enable"`
	// TTL 为上游未给出缓存指令时 200 响应的缓存秒数,0 表示只遵循上游的 Cache-Control
	TTL int `json:"ttl"`
	// MaxMB 为缓存总容量,默认 64
	MaxMB int `json:"maxMb"`
}

CacheConfig 是反向代理的响应缓存(内存)。

type CertSource

type CertSource interface {
	GetCertificate(*tls.ClientHelloInfo) (*tls.Certificate, error)
}

CertSource 提供按 SNI 选择证书的能力(由证书模块实现)。

type ForwardAuth added in v0.5.2

type ForwardAuth struct {
	// URL 为认证接口,例如 Authelia 的 http://127.0.0.1:9091/api/authz/auth-request;留空不启用
	URL string `json:"url"`
	// LoginURL 为认证接口返回 401 时跳转的登录地址,可用 {url}(访客原始地址,已编码)与 {method} 占位,
	// 例如 https://auth.example.com/?rd={url}&rm={method};留空时把认证接口的响应原样返回给访客
	LoginURL string `json:"loginUrl"`
	// CopyHeaders 为认证通过后从认证响应复制到后端请求的头;留空时使用 Remote-User、Remote-Groups、Remote-Email、Remote-Name
	CopyHeaders []string `json:"copyHeaders"`
}

ForwardAuth 把站点的认证交给外部服务(Authelia、Authentik、oauth2-proxy 等), 相当于 nginx 的 auth_request 或 Traefik / Caddy 的 forward_auth。

type HealthCheck added in v0.3.0

type HealthCheck struct {
	Enable bool `json:"enable"`
	// Mode 为 http(请求 Path,状态码 < 400 视为健康)或 tcp(只测试连接)
	Mode string `json:"mode"`
	Path string `json:"path"`
	// Interval / Timeout 单位为秒
	Interval int `json:"interval"`
	Timeout  int `json:"timeout"`
	// Fails 连续失败多少次判为不健康,Passes 连续成功多少次恢复
	Fails  int `json:"fails"`
	Passes int `json:"passes"`
}

HealthCheck 是后端健康检查设置。未启用时仍会做被动检查(连续连接失败后暂时摘除)。

type Listener

type Listener struct {
	Key    string `json:"key"`
	Name   string `json:"name"`
	Enable bool   `json:"enable"`
	// Network 为 tcp(双栈)、tcp4、tcp6
	Network  string `json:"network"`
	ListenIP string `json:"listenIp"`
	Port     int    `json:"port"`
	TLS      bool   `json:"tls"`
	// MinTLS 为 1.0 / 1.1 / 1.2 / 1.3
	MinTLS string `json:"minTls"`
	// HTTP3 在同一端口号的 UDP 上同时提供 HTTP/3(QUIC),需要开启 HTTPS
	HTTP3 bool `json:"http3"`
	// AcceptProxyProtocol 接收上游(如 haproxy、frp)发送的 PROXY 协议头,仅信任全局设置中的来源
	AcceptProxyProtocol bool   `json:"acceptProxyProtocol"`
	Sites               []Site `json:"sites"`
	// Default 在没有站点匹配时使用;未启用时返回 404
	Default Site   `json:"default"`
	Remark  string `json:"remark"`
}

Listener 是一个监听端口及其站点。

func (*Listener) Validate

func (l *Listener) Validate() error

Validate 校验监听器及其站点。

type ListenerView

type ListenerView struct {
	Listener
	Running bool                        `json:"running"`
	Error   string                      `json:"error,omitempty"`
	Stats   map[string]map[string]int64 `json:"stats"`
	// Upstreams 为各站点的后端健康状态,键为站点 key
	Upstreams map[string][]UpstreamStatus `json:"upstreams,omitempty"`
}

ListenerView 是带运行状态的监听器。

type Location added in v0.5.2

type Location struct {
	// Prefix 为路径前缀,按路径段边界匹配:/api 与 /api/ 都匹配 /api 及 /api/x,不匹配 /apix
	Prefix string `json:"prefix"`
	// Targets 为该路径的后端,格式同站点后端;留空时沿用站点后端,只追加请求头
	Targets []string `json:"targets"`
	// RequestHeaders 追加在站点请求头之后,同名时覆盖站点的设置
	RequestHeaders []string `json:"requestHeaders"`
}

Location 把站点下某个路径前缀的请求分到另一组后端,相当于 nginx 的 location /api/ { proxy_pass ...; }。 路径原样转发(不去掉前缀);其余反向代理设置(Host、转发头、TLS 校验等)沿用站点。

type Module

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

Module 是 Web 服务模块。

func New

func New(certs CertSource, waf WAFProvider) *Module

New 创建模块。certs 为证书来源,可为 nil(此时不能启用 HTTPS);waf 可为 nil(站点的 WAF 设置不生效)。

func (*Module) ID

func (m *Module) ID() string

ID 实现 module.Module。

func (*Module) ImportLucky

func (m *Module) ImportLucky(doc luckyimport.Document, opts luckyimport.Options) (*luckyimport.Report, error)

ImportLucky 实现 luckyimport.Importer,同时识别 lucky_base 中的 PROXY 协议可信来源。

func (*Module) Init

func (m *Module) Init(env module.Env) error

Init 实现 module.Module。

func (*Module) Metrics added in v0.5.0

func (m *Module) Metrics() []module.Sample

Metrics 实现 module.Metricer:导出各站点的请求、流量与后端健康指标。

func (*Module) Routes

func (m *Module) Routes(r module.Router)

Routes 实现 module.Module。

func (*Module) Start

func (m *Module) Start(ctx context.Context) error

Start 实现 module.Module。

func (*Module) Stop

func (m *Module) Stop() error

Stop 实现 module.Module。

func (*Module) Summary

func (m *Module) Summary() []module.SummaryItem

Summary 实现 module.Summarizer。

func (*Module) Title

func (m *Module) Title() string

Title 实现 module.Module。

type OAuthProvider

type OAuthProvider = thirdauth.Provider

OAuthProvider 是一个自建的第三方登录配置(使用用户自己申请的 OAuth 应用,不经过任何中转服务器)。

type PathRule added in v0.3.0

type PathRule struct {
	Prefix string `json:"prefix"`
	// Auth 为 ""(沿用站点)、off(无需认证)、on(必须认证)
	Auth   string   `json:"auth"`
	IPMode string   `json:"ipMode"`
	IPList []string `json:"ipList"`
}

PathRule 为某个路径前缀覆盖站点的认证与 IP 访问控制。最长前缀优先。

type Point added in v0.3.0

type Point struct {
	Time     int64 `json:"t"`
	Requests int64 `json:"requests"`
	Bytes    int64 `json:"bytes"`
	S4xx     int64 `json:"s4xx"`
	S5xx     int64 `json:"s5xx"`
}

Point 是一个时间点的统计。

type RateLimit added in v0.3.0

type RateLimit struct {
	Enable bool `json:"enable"`
	// Rate 为每秒允许的请求数,Burst 为突发容量
	Rate  float64 `json:"rate"`
	Burst int     `json:"burst"`
	// MaxConns 为单个 IP 的并发请求上限,0 表示不限
	MaxConns int `json:"maxConns"`
}

RateLimit 按客户端 IP 限流。

type Rewrite added in v0.3.0

type Rewrite struct {
	// Pattern 为匹配请求路径的正则表达式
	Pattern string `json:"pattern"`
	// To 为替换结果,可使用 $1 引用分组;Redirect 时为跳转目标,可用 {host} 代表访客请求的域名
	To       string `json:"to"`
	Redirect bool   `json:"redirect"`
	// Code 为重定向状态码,默认 302
	Code int `json:"code"`
}

Rewrite 是路径重写或重定向规则,按顺序匹配,命中第一条即停止。

type Settings

type Settings struct {
	Enable bool `json:"enable"`
	// TrustedProxies 为可信的 PROXY 协议来源(IP 或 CIDR)
	TrustedProxies []string `json:"trustedProxies"`
	// AuthSecret 用于签名网页认证 Cookie,首次启动自动生成
	AuthSecret string `json:"authSecret"`
	// OAuthProviders 为自建的第三方登录配置
	OAuthProviders []OAuthProvider `json:"oauthProviders"`
	// OAuthCallbackBase 为接收第三方登录回调的站点地址(需由 Gately 的某个监听提供),例如 https://auth.example.com
	OAuthCallbackBase string `json:"oauthCallbackBase"`
	// AutoBanSeconds 为认证连续失败后自动封禁来源 IP 的秒数,0 表示不自动封禁
	AutoBanSeconds int `json:"autoBanSeconds"`
	// AuthUsers 为可在多个站点共用的认证用户,站点开启“使用共享用户”后生效
	AuthUsers []AuthUser `json:"authUsers"`
	// SSODomain 为共享用户登录态的 Cookie 域(如 example.com),设置后该域及其子域名下的站点登录一次即可通用
	SSODomain string `json:"ssoDomain"`
}

Settings 是模块级配置。

type ShareLink struct {
	Key  string `json:"key"`
	Name string `json:"name"`
	// Token 是访问令牌,访问 https://域名/任意路径?_gs=令牌 即可兑换会话
	Token     string    `json:"token"`
	ExpiresAt time.Time `json:"expiresAt,omitzero"`
	// MaxUses 为最多可被兑换的次数,0 表示不限;重启后计数清零
	MaxUses int `json:"maxUses"`
	// PathPrefix 非空时,链接只能访问该前缀下的路径
	PathPrefix string `json:"pathPrefix"`
}

ShareLink 是站点的临时分享链接:持有令牌的访客无需账号即可在有效期内访问。

type Site

type Site struct {
	Key    string `json:"key"`
	Name   string `json:"name"`
	Enable bool   `json:"enable"`
	// Domains 支持精确域名、*.example.com 通配(匹配任意级子域名)与 *(匹配所有)
	Domains []string `json:"domains"`
	Type    string   `json:"type"`

	// 反向代理
	Targets            []string `json:"targets"`
	InsecureSkipVerify bool     `json:"insecureSkipVerify"`
	// UseTargetHost 为 true 时 Host 头使用目标地址,否则保留客户端请求的 Host
	UseTargetHost     bool `json:"useTargetHost"`
	DisableKeepAlives bool `json:"disableKeepAlives"`
	// SendProxyProtocol 向后端发送 PROXY v2 头传递真实客户端 IP(需要后端支持)
	SendProxyProtocol bool `json:"sendProxyProtocol"`
	// ForwardedHeaders 添加 X-Forwarded-For/Proto/Host/Port 与 X-Real-IP
	ForwardedHeaders bool `json:"forwardedHeaders"`
	// UpstreamSNIFromHost 为 true 时连接 HTTPS 后端使用访客请求的域名作为 SNI 并按它校验证书
	// (相当于 nginx 的 proxy_ssl_server_name on + proxy_ssl_name $host),后端按 SNI 分流时(如 frp 的 vhost_https)需要开启
	UpstreamSNIFromHost bool `json:"upstreamSniFromHost"`
	// Locations 为按路径前缀分到不同后端的规则,最长前缀优先,未命中时使用站点后端
	Locations []Location `json:"locations"`

	// 重定向:RedirectTo 为目标地址前缀,可用 {host} 代表访客请求的域名;KeepPath 时附加原路径与查询串
	RedirectTo   string `json:"redirectTo"`
	RedirectCode int    `json:"redirectCode"`
	KeepPath     bool   `json:"keepPath"`

	// 静态文件
	Root    string `json:"root"`
	ListDir bool   `json:"listDir"`
	// CleanURLs 时找不到文件会再尝试 路径.html 与 路径/index.html
	CleanURLs bool `json:"cleanUrls"`
	// NotFoundPage 为文件不存在时返回的页面,相对 Root 的路径,例如 404.html
	NotFoundPage string `json:"notFoundPage"`

	// 固定文本
	Text        string `json:"text"`
	ContentType string `json:"contentType"`
	StatusCode  int    `json:"statusCode"`

	// 认证:Users 每项为 用户名:密码(密码可为 bcrypt 哈希)
	BasicAuth bool     `json:"basicAuth"`
	WebAuth   bool     `json:"webAuth"`
	Users     []string `json:"users"`
	// SharedUsers 为 true 时网页认证与基本认证也接受全局设置中的共享用户(支持 TOTP 与跨站单点登录)
	SharedUsers bool `json:"sharedUsers"`
	// OAuthUsers 为允许通过第三方登录访问的身份,格式 提供方key:标识(用户名、邮箱、稳定 ID 均可,行尾可用 " #" 加备注),提供方key:* 表示该提供方任意用户
	OAuthUsers []string `json:"oauthUsers"`

	IPMode string   `json:"ipMode"`
	IPList []string `json:"ipList"`

	// CountryMode 为 ""(不限)、allow(仅允许列出的国家)、deny(拒绝列出的国家),需先在设置中导入 GeoIP 数据库
	CountryMode string `json:"countryMode"`
	// Countries 为两位 ISO 国家代码,如 CN、US
	Countries []string `json:"countries"`
	// ForwardAuth 把认证交给外部服务(如 Authelia),与基本认证、网页认证不能同时使用
	ForwardAuth ForwardAuth `json:"forwardAuth"`
	// AuthOptional 为 true 时,认证只作用于路径规则中标记为"必须认证"的路径,其余路径公开
	AuthOptional bool `json:"authOptional"`
	// Rules 为按路径前缀覆盖认证与 IP 访问控制的规则
	Rules []PathRule `json:"rules"`
	// ShareLinks 为临时分享链接,持令牌访客可绕过认证
	ShareLinks []ShareLink `json:"shareLinks"`

	// 反向代理增强:Targets 每项可附 weight=N、backup;LBPolicy 为 ""(轮询)、random、ip_hash、least_conn
	LBPolicy  string      `json:"lbPolicy"`
	Health    HealthCheck `json:"health"`
	Compress  bool        `json:"compress"`
	RateLimit RateLimit   `json:"rateLimit"`
	Cache     CacheConfig `json:"cache"`
	Rewrites  []Rewrite   `json:"rewrites"`

	// RequestHeaders / ResponseHeaders 每项为 "Key: Value",Value 为空表示删除该头
	RequestHeaders  []string `json:"requestHeaders"`
	ResponseHeaders []string `json:"responseHeaders"`
	CORS            bool     `json:"cors"`
	AccessLog       bool     `json:"accessLog"`
	// WAF 为引用的 WAF 实例 key,留空不检查;实例不存在或停用时放行
	WAF    string `json:"waf"`
	Remark string `json:"remark"`
	// contains filtered or unexported fields
}

Site 是监听器下按域名匹配的一个站点。

type SiteStats

type SiteStats struct {
	Requests atomic.Int64
	Active   atomic.Int64
	Errors   atomic.Int64
}

SiteStats 是站点的请求统计。

type SiteStatsView added in v0.3.0

type SiteStatsView struct {
	Series       []Point          `json:"series"`
	Status       map[string]int64 `json:"status"`
	BytesOut     int64            `json:"bytesOut"`
	TopIPs       []TopItem        `json:"topIps"`
	TopCountries []TopItem        `json:"topCountries"`
	Upstreams    []UpstreamStatus `json:"upstreams,omitempty"`
}

SiteStatsView 是站点统计接口的输出。

type TopItem added in v0.3.0

type TopItem struct {
	Key   string `json:"key"`
	Count int64  `json:"count"`
}

TopItem 是排行榜的一项。

type UpstreamStatus added in v0.3.0

type UpstreamStatus struct {
	URL     string `json:"url"`
	Weight  int    `json:"weight"`
	Backup  bool   `json:"backup"`
	Healthy bool   `json:"healthy"`
	Conns   int64  `json:"conns"`
}

UpstreamStatus 是后端状态快照。

type WAFProvider

type WAFProvider interface {
	Middleware(key string, next http.Handler) http.Handler
}

WAFProvider 提供按实例检查请求的中间件(由 WAF 模块实现)。

Jump to

Keyboard shortcuts

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