vweb

package module
v3.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: Apache-2.0 Imports: 41 Imported by: 1

README

vweb

一个用 Go 编写的高性能、模块化、可扩展的 Web 服务器框架,内置多站点托管、动态模板执行、插件化 RPC/HTTP 通信、配置热重载、Let's Encrypt 自动证书等能力。


特性

  • 多站点托管:一个进程管理多个站点,按 Host 隔离;支持通配符域名匹配(如 *.example.com)。
  • 多监听地址:通过配置即可同时启动任意数量的 IP:Port 监听;服务器连接参数与 TLS 可独立配置。
  • 动态模板执行:支持 Yaegi(Go 解释器)、Ixgo/Igop、Wazero(WASM)等动态引擎;同一站点可按文件后缀路由到不同引擎。
  • 路由能力:
    • 精确匹配(O(1))
    • 正则匹配(以 ^、$ 界定)
    • 通配符匹配([]*?\)
    • 占位符匹配(如 /user/{id}、b{id}b)
  • 反向代理 / URL 重写:规则在配置加载阶段预编译;支持重定向、排除路径、连续匹配。
  • 插件系统:
    • PluginRPC:基于 net/rpc + gob 的 RPC 连接池
    • PluginHTTP:基于 http.Transport 的反向代理
  • 会话管理:可配置名称、ID 长度、过期时间、加盐;支持 Defer 退出回调与哈希失效。
  • 全局缓存与会话:基于 vmap,支持键级别过期、过期回调、重置。
  • 静态文件服务:支持 GET/HEAD、Range(单/多区间、后缀区间)、ETag、If-None-Match、If-Range、Cache-Control 等。
  • HTTPS 支持:
    • 手动加载证书(PEM/DER/CRT)
    • Let's Encrypt autocert 自动申请与缓存
    • 白名单 host.txt 动态热重载
  • 配置热重载:config.json / config.toml 变更后自动重载并重建站点、服务器与插件。
  • 优雅关闭:服务组 Close、站点池 Close、动态模板 Close 全部保证清理与 Defer 执行。
  • 健壮性:并发安全、反射越界防护、路径穿越防护、WASM 头探测、临时文件原子提交等。
  • 内置解释器:builtin 包提供动态模板可用的 Get/Set/Make/Compute/Len/Append/Copy/Convert/Init/CopyStruct 等函数,兼顾安全与性能。

快速开始

编译
git clone https://github.com/456vv/vweb.git
cd vweb
go build -o vweb ./cmd/main

需要 Go 1.22+(依赖 reflect.TypeFor、for range int、maps.Copy 等特性)。

运行
./vweb -RootDir=/opt/vweb -ConfigFile=config.json -LogFile=error.log

启动参数

参数 默认值 说明
-RootDir 程序所在目录 程序根目录(会 chdir)
-ConfigFile config.json 主配置文件路径
-LogFile error.log 日志文件
-CertCache ssl/auto Let's Encrypt 证书缓存目录
-AllowCertHost ssl/auto/host.txt 自动申请证书的域名白名单

注意:不带任何 flag 时会打印帮助后退出(flag.NFlag() == 0)。


项目结构

vweb/
├── builtin/              # 动态模板内置函数库(Get/Set/Compute/Make/Convert…)
├── cmd/main/             # 可执行入口
│   ├── internal/
│   │   ├── base/         # 信号处理(跨平台)
│   │   └── dynamic/      # 动态引擎注册表(Yaegi/Ixgo/Wazero)
│   ├── func.go           # 自动证书白名单加载
│   └── main.go           # 主入口
├── plugin/               # 独立 RPC/HTTP 插件服务器
├── server/               # 服务组、监听器、配置解析
│   ├── config/           # 配置文件结构 & 合并逻辑
│   ├── Server.go         # http.Server 封装
│   ├── listener.go       # TCP/KeepAlive/TLS 监听器
│   ├── plugin.go         # 插件客户端管理
│   └── func.go           # 通配符域名、请求头处理
├── PluginRPC.go          # RPC 插件客户端
├── pluginHTTP.go         # HTTP 插件客户端
├── dot.go                # Dot 上下文(模板点)
├── route.go              # 路由系统
├── rewrite.go            # URL 重写
├── response.go           # Response 封装
├── serverHandlerDynamic.go # 动态模板处理
├── serverHandlerStatic.go  # 静态文件处理
├── sessions.go           # 会话管理
├── Session.go            # 单个会话
├── Site.go               # 站点与站点池
├── cookie.go             # Cookie 工具
├── defer.go              # 延迟调用
├── func.go               # 工具函数(随机 ID、域名匹配等)
├── reflect.go            # 反射调试输出
└── vweb.go               # 包常量与上下文 key

配置文件

主配置 config.json
{
  "Servers": {
    "Public": {
      "CC": {
        "default": {
          "KeepAlive": true,
          "KeepAlivePeriod": 180000,
          "NoDelay": true
        }
      },
      "CS": {
        "default": {
          "ReadTimeout": 15000,
          "WriteTimeout": 60000,
          "IdleTimeout": 60000,
          "KeepAlivesEnabled": true,
          "ShutdownConn": true
        }
      }
    },
    "Listen": {
      ":8080": {
        "Status": true,
        "CC": { "PublicName": "default" },
        "CS": { "PublicName": "default" }
      },
      ":8443": {
        "Status": true,
        "CC": { "PublicName": "default" },
        "CS": {
          "PublicName": "default",
          "TLS": {
            "RootCAs": [
              { "CertFile": "ssl/server.crt", "KeyFile": "ssl/server.key" }
            ],
            "MinVersion": 771,
            "NextProtos": ["h2", "http/1.1"]
          }
        }
      }
    }
  },
  "Sites": {
    "Public": {
      "Session": {
        "default": { "Name": "SID", "Size": 64, "Expired": 1200 }
      },
      "Header": {
        "default": {
          "MIME": { ".wasm": "application/wasm" },
          "Static": {
            ".*": { "PageExpired": 3600 }
          }
        }
      }
    },
    "Site": [
      {
        "Status": true,
        "Name": "示例站点",
        "Identity": "example",
        "Host": ["example.com", "*.example.com"],
        "IndexFile": ["index.html", "index.go"],
        "Directory": {
          "Root": "/srv/web/example",
          "Virtual": ["/static/"]
        },
        "Session": { "PublicName": "default" },
        "Header":  { "PublicName": "default" },
        "Dynamic": {
          "Ext": [".go"],
          "Cache": true,
          "CacheParseTimeout": 300
        },
        "Forward": {
          "example.com": {
            "List": [
              {
                "Status": true,
                "Path": ["^/api/(.*)$"],
                "RePath": "/gateway/$1",
                "End": true
              }
            ]
          }
        },
        "Plugin": {
          "HTTP": {
            "gw": {
              "Status": true,
              "Addr": "127.0.0.1:9000",
              "Scheme": "http",
              "Timeout": 3000
            }
          }
        },
        "ErrorPage": {
          "404": "404.html",
          "500": "500.html"
        }
      }
    ]
  }
}
子配置文件

主配置所在目录下的以下文件会被自动加载并合并:

  • *.site.json / *.site.toml:按 Identity 合并站点列表(同名替换、异名追加)
  • *.listen.json / *.listen.toml:合并监听地址

TOML 示例:

[[Site]]
Status = true
Name = "示例站点"
Identity = "example"
Host = ["example.com"]
IndexFile = ["index.html"]

[Site.Directory]
Root = "/srv/web/example"

路由

route := new(vweb.Route)

// 精确匹配
route.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("ok"))
})

// 正则匹配
route.HandleFunc(`^/api/v\d+/`, func(w http.ResponseWriter, r *http.Request) { /* ... */ })

// 通配符匹配
route.HandleFunc("/static/*", func(w http.ResponseWriter, r *http.Request) { /* ... */ })

// 占位符匹配
route.HandleFuncDot("/user/{id}", func(d vweb.Doter) {
    params, _ := d.Context().Value("url-params").(map[string]string)
    d.Response().WriteString("id=" + params["id"])
})

占位符规则:

  • {name} 提取任意非空值
  • b{id}b 支持前后缀
  • 不允许相邻占位符 {a}{b}

插件系统

RPC 插件(PluginRPC)
c := &vweb.PluginRPCClient{
    ConnPool: vconnpool.NewPool(),
    Addr:     "127.0.0.1:9001",
    Path:     "/_rpc",
}
rpc, err := c.Connection()
if err != nil { /* ... */ }
defer rpc.Discard()

var reply string
err = rpc.Call("Example.Hello", "world", &reply)

服务端可使用 plugin.NewServerRPC():

srv := plugin.NewServerRPC()
srv.RegisterName("Example", new(ExampleService))
srv.HandleHTTP("/_rpc", "/_rpc/debug")
srv.Addr = ":9001"
srv.ListenAndServe()
HTTP 插件(PluginHTTP)
c := &vweb.PluginHTTPClient{
    Tr:     &http.Transport{},
    Addr:   "127.0.0.1:9000",
    Scheme: "http",
    Host:   "backend",
}
p, _ := c.Connection()
// p 直接实现 http.Handler
http.ListenAndServe(":8080", p)

动态模板

ServerHandlerDynamic 依据文件第一行(注释)或 WASM 文件头选择动态引擎:

  • 首行 // yaegi → Yaegi
  • 首行 // igop / // ixgo → Ixgo
  • 首行 // wasm-01000000 或 WASM 二进制(\0asm)→ Wazero

一个动态文件示例:

// yaegi
package main

import "github.com/456vv/vweb/v3"

func Main(d vweb.Doter) {
    d.Response().WriteString("Hello, " + d.Request().URL.Path)
}

请求路径会映射为执行入口函数名(index.go → Main,about.go → About)。


会话与缓存

// 在 Dot 中访问
s := d.Session()      // Sessioner
s.Set("uid", 42)
uid := s.Get("uid")

g := d.Global()       // Globaler
g.SetExpiredCall("token", 5*time.Minute, func(v any) {
    log.Println("token expired:", v)
})

会话 ID 的生成、加盐、Cookie 写入、过期扫描由 Sessions 统一处理;InstantDeadAll 会遍历并清理全部会话并执行 Defer。


自动证书(Let's Encrypt)

cmd/main 内置 autocert.Manager:

  • 证书缓存到 -CertCache 目录
  • 域名白名单由 -AllowCertHost 文件控制(每行一个域名,# 注释)
  • 文件变更后自动重载
  • 白名单为空时 默认拒绝 一切自动申请(HostPolicy 返回错误)

优雅关闭

group := server.NewGroup()
// ...
base.StartSigHandlers()

go func() {
    <-base.Interrupted
    group.Close()
}()

Group.Close 会:

  1. 停止所有监听(ShutdownConn=true 时优雅关闭,否则立即关闭)
  2. 清理 srvMan 中的服务器
  3. 清理全部站点、插件、动态模板缓存、会话、全局数据
  4. 关闭 sitePool(最多等待 3 秒让 Defer 完成)

贡献

欢迎通过 GitHub Issue / Pull Request 反馈问题或贡献代码。提交前请确保:

  • go build ./... 与 go vet ./... 通过
  • 关键路径覆盖测试(尤其是并发与生命周期)
  • 配置/协议变更请同步更新文档与示例

许可

本项目基于仓库中 LICENSE 文件所示的许可证发布。若未附带 LICENSE 文件,请在使用前联系作者确认授权条款。

部分源自 Go 标准库的代码(如 cmd/main/internal/base/signal*.go)保留其 BSD 风格版权声明。


致谢

感谢所有依赖项目作者与贡献者的开源工作。

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	SiteContextKey     = &contextKey{"web-site"}     // 当前站点 *Site
	RouterContextKey   = &contextKey{"web-router"}   // 路由相关对象
	ListenerContextKey = &contextKey{"web-listener"} // 监听器
	ConnContextKey     = &contextKey{"web-conn"}     // 底层连接
	PluginContextKey   = &contextKey{"web-plugin"}   // 插件管理器
)

请求上下文中预定义的 Key,可在 Handler / 模板 / 中间件中通过 req.Context().Value(...) 取出。

示例:

if site, ok := req.Context().Value(vweb.SiteContextKey).(*vweb.Site); ok {
    // 使用 site
}

Functions

func AddSalt

func AddSalt(rnd []byte, salt string) string

AddSalt 加盐

rnd []byte	标识字节串
salt string	盐
string  	标识符

func AutoCert

func AutoCert(ac *autocert.Manager, tlsconf *tls.Config, handler http.Handler) http.Handler

AutoCert 自动从 Let's Encrypt 申请证书

ac *autocert.Manager	申请证书管理
tlsconf *tls.Config		tls配置
handler http.Handler	http处理

func ExecFunc

func ExecFunc(f any, args ...any) ([]any, error)

ExecFunc 执行函数调用

call any            函数
args ... any        参数或更多个函数是函数的参数
[]any				返回直
error                       错误

func ForMethod

func ForMethod(x any) string

ForMethod 遍历并返回方法信息

func ForType

func ForType(x any, showUnexported bool, maxDepth int) string

ForType 遍历字段 x: 目标对象 showUnexported: 是否展示小写(未导出)字段 maxDepth: 最大递归深度

func GenerateRandom

func GenerateRandom(length int) ([]byte, error)

GenerateRandom 生成标识符

length int	长度
[]byte  	生成的标识符
err error	错误

func GenerateRandomID

func GenerateRandomID(rnd []byte) error

GenerateRandomID 生成标识符

[]byte  	生成的标识符
err error	错误

func GenerateRandomString

func GenerateRandomString(length int) (string, error)

GenerateRandomString 生成标识符

length int	长度
string  	生成的标识符
err error	错误

func PagePath

func PagePath(root, p string, index []string) (os.FileInfo, string, error)

PagePath 页路径

root string		    根目录
p string            路径
index []string      索引文件名
os.FileInfo         文件信息
string          	路径
error				错误,如果文件不存在

Types

type Cookie struct {
	R *http.Request       // 请求
	W http.ResponseWriter // 响应
}

Cookie 类型定义。

func (*Cookie) Add

func (c *Cookie) Add(name, value, path, domain string, maxAge int, secure, only bool, sameSite http.SameSite)

Add 增加,写入一条Cookie,可以写入多条Cookie保存至浏览器

func (*Cookie) Del

func (c *Cookie) Del(name string)

Del 删除,删除指定的Cookie

name string            名称

func (*Cookie) Get

func (c *Cookie) Get(name string) string

Get 读取Cookie,如果不存在返回空字符

name string     指定名称读取的Cookie
string          返回值

func (*Cookie) ReadAll

func (c *Cookie) ReadAll() map[string]string

ReadAll 读出所有Cookie

map[string]string        读取出所有Cookie

func (*Cookie) RemoveAll

func (c *Cookie) RemoveAll()

RemoveAll 移除所有Cookie

type Cookier

type Cookier interface {
	ReadAll() map[string]string                                                                  // 读取所有
	RemoveAll()                                                                                  // 删除所用
	Get(name string) string                                                                      // 读取
	Add(name, value, path, domain string, maxAge int, secure, only bool, sameSite http.SameSite) // 增加
	Del(name string)                                                                             // 删除
}

Cookier 类型定义。

type Dot

type Dot struct {
	R *http.Request       // 请求
	W http.ResponseWriter // 响应

	Site *Site // 网站配置
	// contains filtered or unexported fields
}

Dot 模板点

func (*Dot) Close

func (T *Dot) Close() error

Close 释放

func (*Dot) Context

func (T *Dot) Context() context.Context

Context 上下文

context.Context 上下文

func (*Dot) Cookie

func (T *Dot) Cookie() Cookier

Cookie 用户的Cookie

Cookier	接口

func (*Dot) Defer

func (T *Dot) Defer(call any, args ...any) error

Defer 在用户会话时间过期后,将被调用。

	call any            函数
	args ... any        参数或更多个函数是函数的参数
	error                       错误
 例:
	.Defer(fmt.Println, "1", "2")
	.Defer(fmt.Printf, "%s", "汉字")

func (*Dot) Global

func (T *Dot) Global() Globaler

Global 全站缓存

Globaler	公共缓存

func (*Dot) Header

func (T *Dot) Header() http.Header

Header 标头

http.Header   响应标头

func (*Dot) Request

func (T *Dot) Request() *http.Request

Request 用户的请求信息

*http.Request 请求

func (*Dot) RequestLimitSize

func (T *Dot) RequestLimitSize(l int64) *http.Request

RequestLimitSize 请求限制大小

l int64         复制body大小
*http.Request   请求

func (*Dot) Response

func (T *Dot) Response() Responser

Response 数据写入响应

Responser     响应

func (*Dot) RootDir

func (T *Dot) RootDir(upath string) string

RootDir 网站的根目录

upath string	页面路径
string 			根目录

func (*Dot) SaveStatic

func (T *Dot) SaveStatic(path string) (wr io.WriteCloser, err error)

SaveStatic 保存为静态文件

func (*Dot) Session

func (T *Dot) Session() Sessioner

Session 用户的会话缓存

Sessioner  会话缓存

func (*Dot) Swap

func (T *Dot) Swap() *vmap.Map

Swap 信息交换

Swaper  映射

func (*Dot) WithContext

func (T *Dot) WithContext(ctx context.Context)

WithContext 替换上下文

ctx context.Context 上下文

type DotContexter

type DotContexter interface {
	Context() context.Context        // 上下文
	WithContext(ctx context.Context) // 替换上下文
}

DotContexter 类型定义。

type Doter

type Doter interface {
	RootDir(path string) string                            // 网站的根目录
	Request() *http.Request                                // 用户的请求信息
	RequestLimitSize(l int64) *http.Request                // 请求限制大小
	Header() http.Header                                   // 标头
	Response() Responser                                   // 数据写入响应
	Session() Sessioner                                    // 用户的会话缓存
	Global() Globaler                                      // 全站缓存
	Cookie() Cookier                                       // 用户的Cookie
	Swap() *vmap.Map                                       // 信息交换
	Defer(call any, args ...any) error                     // 退回调用
	SaveStatic(path string) (wr io.WriteCloser, err error) // 保存为静态文件
	DotContexter                                           // 上下文
}

Doter 可以在模本中使用的方法

type DynamicTemplateFunc

type DynamicTemplateFunc func(*ServerHandlerDynamic) DynamicTemplater

DynamicTemplateFunc 声明动态模板获取函数类型

type DynamicTemplater

type DynamicTemplater interface {
	SetPath(root string, page string)
	Parse(r io.Reader) (err error)                        // 解析模板内容
	Execute(name string, out io.Writer, dot ...any) error // 执行模板并输出
	Close() error                                         // 释放相关资源
}

DynamicTemplater 动态模板接口规范

type ExecCall

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

ExecCall 执行函数包装器

func (*ExecCall) Exec

func (T *ExecCall) Exec() []any

Exec 执行函数

func (*ExecCall) Func

func (T *ExecCall) Func(call any, args ...any) error

Func 初始化函数和参数

type ExitCall

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

ExitCall 任务管理

func (*ExitCall) Defer

func (T *ExitCall) Defer(call any, args ...any) error

注册回调。 参数 call: 函数;args: 参数。

func (*ExitCall) Free

func (T *ExitCall) Free()

执行队列中全部回调。

type Forward

type Forward struct {
	Path        []string // 多种路径匹配
	ExcludePath []string // 排除多种路径匹配
	RePath      string   // 重写路径
}

Forward 原始配置结构

func (*Forward) Compile

func (T *Forward) Compile() (*ForwardRewriter, error)

Compile 预编译正则,建议在程序初始化或配置加载时调用一次。 返回的 *ForwardRewriter 可被多 goroutine 并发安全地调用 Rewrite。

type ForwardRewriter

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

ForwardRewriter 编译后的执行对象

func (*ForwardRewriter) Rewrite

func (T *ForwardRewriter) Rewrite(upath string) (string, bool)

Rewrite 对给定路径进行重写。 返回值:(重写后的路径, 是否发生了重写) 方法本身是并发安全的,可在多个 goroutine 中同时调用。

type Global added in v3.4.2

type Global struct {
	*vmap.Map
}

Global 站点全局数据,内嵌 vmap.Map。

func (*Global) Reset added in v3.4.2

func (T *Global) Reset()

实现说明:Global 通过内嵌 *vmap.Map 满足 Globaler 的大部分方法; 具体方法由 vmap 提供,此处无需再包装。

type Globaler

type Globaler interface {
	Set(key, val any)                                     // 设置
	Has(key any) bool                                     // 判断
	Get(key any) any                                      // 读取
	GetHas(key any) (val any, ok bool)                    // 读取判断
	Del(key any)                                          // 删除
	SetExpired(key any, d time.Duration)                  // 过期
	SetExpiredCall(key any, d time.Duration, f func(any)) // 过期调用
	TTL(key any) (time.Duration, bool)                    // 某个KEY过期时间
	Range(f func(key, value any) bool)                    // 遍历
	Reset()                                               // 重置
}

Globaler 站点级全局键值存储接口(与 Session 类似,但作用于整个站点,非单用户)。

type HandleFunc

type HandleFunc []func(Doter)

HandleFunc 类型定义。

func (HandleFunc) ServeHTTP

func (T HandleFunc) ServeHTTP(w http.ResponseWriter, r *http.Request)

type PluginHTTP

type PluginHTTP interface {
	Type() PluginType                                           // 类型
	ServeHTTP(w http.ResponseWriter, r *http.Request)           // 服务HTTP
	RoundTrip(r *http.Request) (resp *http.Response, err error) // 代理
	CancelRequest(req *http.Request)                            // 取消HTTP请求
	CloseIdleConnections()                                      // 关闭空闲连接
	RegisterProtocol(scheme string, rt http.RoundTripper)       // 注册新协议
}

PluginHTTP http插件接口

type PluginHTTPClient

type PluginHTTPClient struct {
	Tr     *http.Transport // 客户端
	Addr   string          // 地址
	Scheme string          // 协议(用于默认填充)
	Host   string          // 请求Host(用于默认填充)
	Dialer *net.Dialer
	// contains filtered or unexported fields
}

PluginHTTPClient 插件HTTP客户端

func (*PluginHTTPClient) Connection

func (T *PluginHTTPClient) Connection() (PluginHTTP, error)

Connection 快速连接HTTP

PluginHTTP	插件HTTP
error		错误

type PluginRPC

type PluginRPC interface {
	Type() PluginType                           // 类型,固定返回 PluginTypeRPC
	Register(value any)                         // 注册 struct 类型(gob)
	Call(name string, arg any, reply any) error // 远程调用
	Discard() error                             // 废弃连接(不回池)
	Close() error                               // 关闭并回池(若支持)
}

PluginRPC rpc 插件接口。 用于与后端 RPC 服务通信:注册类型、发起调用、丢弃或关闭连接。

典型流程:

client := &PluginRPCClient{ConnPool: pool, Addr: "127.0.0.1:9000", Path: "/_goRPC_"}
rpc, err := client.Connection()
rpc.Register(MyType{})
err = rpc.Call("Service.Method", arg, &reply)
rpc.Close() // 或 Discard() 不回收连接

type PluginRPCClient

type PluginRPCClient struct {
	ConnPool *vconnpool.Pool // 连接池(不可为空)
	Addr     string          // 如 "127.0.0.1:9000"
	Path     string          // 如 "/_goRPC_"
}

PluginRPCClient 插件 RPC 客户端配置。 ConnPool 负责连接复用;Addr 为 TCP 地址;Path 为 HTTP CONNECT 路径。

func (*PluginRPCClient) Connection

func (T *PluginRPCClient) Connection() (PluginRPC, error)

Connection 从连接池拨号并建立 Go net/rpc 客户端。

返回:

  • PluginRPC: 可用的 RPC 句柄
  • error: ConnPool 为空、拨号失败、CONNECT 握手失败等

示例:

prpc, err := client.Connection()
if err != nil { return err }
defer prpc.Close()

type PluginType

type PluginType int

PluginType 插件类型枚举(具体定义可能在其它文件,此处仅作类型别名用途说明)。 常见取值:PluginTypeRPC、PluginTypeHTTP 等。

const (
	PluginTypeRPC PluginType = iota
	PluginTypeHTTP
)

type Pluginer

type Pluginer interface {
	RPC(name string) (PluginRPC, error)
	HTTP(name string) (PluginHTTP, error)
}

本文件仅作包级占位;实际插件接口见 PluginRPC.go、pluginHTTP.go。

type Responser

type Responser interface {
	Write([]byte) (int, error)                        // 写入字节
	WriteString(string) (int, error)                  // 写入字符串
	ReadFrom(io.Reader) (int64, error)                // 读取并写入
	Redirect(string, int)                             // 转向
	WriteHeader(int)                                  // 状态码
	Header() http.Header                              // 标头
	Error(string, int)                                // 错误
	Flush()                                           // 刷新缓冲
	Push(target string, opts *http.PushOptions) error // HTTP/2推送
	Hijack() (net.Conn, *bufio.ReadWriter, error)     // 劫持,能双向互相发送信息
}

Responser 类型定义。

type Route

type Route struct {
	HandlerError http.HandlerFunc // 错误访问处理
	// contains filtered or unexported fields
}

Route 类型定义。

func (*Route) HandleFunc

func (T *Route) HandleFunc(url string, handler func(w http.ResponseWriter, r *http.Request))

HandleFunc 绑定处理函数,匹配的网址支持正则,这说明你要严格的检查。

url string                                          网址,支持正则匹配
handler func(w ResponseWriter, r *Request)    		处理函数

func (*Route) HandleFuncDot

func (T *Route) HandleFuncDot(url string, handler ...func(Doter))

注册路径与 Handler。

func (*Route) ServeHTTP

func (T *Route) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP 服务HTTP

w ResponseWriter    响应
r *Request          请求

func (*Route) SetSiteMan

func (T *Route) SetSiteMan(siteMan *SiteMan)

SetSiteMan 设置站点管理,将会携带在请求上下文中 siteMan *SiteMan 站点

type Router added in v3.0.3

type Router interface {
	HandleFunc(url string, handler func(w http.ResponseWriter, r *http.Request))
	HandleFuncDot(url string, handler ...func(Doter))
	ServeHTTP(w http.ResponseWriter, r *http.Request)
}

路由注册与匹配。

type ServerHandlerDynamic

type ServerHandlerDynamic struct {
	// RootPath 网站根目录;PagePath 固定使用的页面路径(可选)
	RootPath, PagePath string

	// 可选的配置
	Site   *Site                                       // 网站配置
	Module func(name string) (DynamicTemplater, error) // 根据解析的首行识别动态文件类型对应的解释器

	// 读取文件。仅在 .ServeHTTP 方法中使用,可外接特殊存储介质。
	//   - 非 nil 时:RootPath 视为逻辑前缀,filePath = path.Join(RootPath, pagePath);
	//     不访问本地文件系统,不做符号链接校验;
	//     仍对请求路径做字符串级 ".." 穿越检查,存储介质内的安全由 ReadFile 实现负责。
	//     返回值中的 reader 必须非 nil(若只需探测 mtime 请仍返回一个可 Close 的空 reader,
	//     或直接返回 io.NopCloser(bytes.NewReader(nil)))。
	//   - 为 nil 时走本地文件系统(os.Stat / os.OpenFile + 符号链接逃逸校验)。
	ReadFile func(filePath string, u *url.URL) (io.ReadCloser, time.Time, error)
	// contains filtered or unexported fields
}

ServerHandlerDynamic 处理动态页面文件并作缓存管理。

func (*ServerHandlerDynamic) Close added in v3.0.5

func (T *ServerHandlerDynamic) Close() error

Close 关闭整个处理器缓存释放相关持有资源。

func (*ServerHandlerDynamic) ServeHTTP

func (T *ServerHandlerDynamic) ServeHTTP(rw http.ResponseWriter, req *http.Request)

ServeHTTP 服务 HTTP 请求

rw http.ResponseWriter    响应写入流
req *http.Request         当前客户端请求

ServeHTTP 服务 HTTP 请求。

type ServerHandlerStatic

type ServerHandlerStatic struct {
	RootPath, PagePath string
	PageExpired        int64 // 缓存过期时长(单位:秒),0则不缓存
}

ServerHandlerStatic 静态文件服务配置

func (*ServerHandlerStatic) ServeHTTP

func (T *ServerHandlerStatic) ServeHTTP(rw http.ResponseWriter, req *http.Request)

ServeHTTP 实现 http.Handler 接口,处理文件读取与响应。

两阶段设计:

  1. os.Stat + 基础头 + 缓存协商:命中 304 直接返回,不 Open 文件;
  2. 未命中才 Open,并用 fstat 与第一阶段 Stat 对比;若文件在 Stat 与 Open 之间被替换(mtime/size 变化),用新 fileInfo 重做缓存协商与 Range 解析, 保证 Content-Length、ETag、Range 与正文读的是同一个文件版本(S1)。

type Session

type Session struct {
	vmap.Map // 数据,用户存储的数据
	// contains filtered or unexported fields
}

Session 会话用于用户保存数据。 内嵌 vmap.Map 提供线程安全的键值存储;id 由 Sessions 管理;exitCall 在 Free 时执行。

func (*Session) Defer

func (T *Session) Defer(call any, args ...any) error

Defer 在用户会话时间过期或被销毁后将被调用。

参数:

  • call: 函数(任意可调用对象)
  • args: 传给该函数的参数,或后续更多函数

返回:若会话已 Free 则返回 "has execute freed"

示例:

.Defer(fmt.Println, "1", "2")
.Defer(fmt.Printf, "%s", "汉字")

func (*Session) Free

func (T *Session) Free()

Free 执行结束 Defer 和键值有效期清理。 幂等:多次调用安全;设置 freed 后禁止再 Defer。

func (*Session) Reset added in v3.4.2

func (T *Session) Reset()

Reset 清空会话内所有键值(等价于 ExpireAll)。 示例:sess.Reset()

func (*Session) Token

func (T *Session) Token() string

Token 读取当前的令牌(会话 ID)。

返回:如 "a1b2c3d4..." 的十六进制或加盐字符串

type Sessioner

type Sessioner interface {
	Token() string                                        // 会话唯一编号(Cookie 值)
	Set(key, val any)                                     // 设置键值
	Has(key any) bool                                     // 是否存在键
	Get(key any) any                                      // 读取(不存在返回 nil)
	GetHas(key any) (val any, ok bool)                    // 读取并判断是否存在
	Del(key any)                                          // 删除单键
	Dels(keys []any)                                      // 批量删除
	SetExpired(key any, d time.Duration)                  // 为键设置过期时间
	SetExpiredCall(key any, d time.Duration, f func(any)) // 过期时调用回调
	TTL(key any) (time.Duration, bool)                    // 查询键剩余存活时间
	Reset()                                               // 清空所有键(触发过期清理)
	Defer(call any, args ...any) error                    // 会话销毁时执行的延迟回调
}

Sessioner 用户独立的内存存储接口。 每个会话对应一个浏览器/客户端,可在请求间保存任意键值,并支持过期与退出回调。

典型用法:

sess := site.Sessions().Session(w, r)
sess.Set("user_id", 42)
if v, ok := sess.GetHas("user_id"); ok { ... }

type Sessions

type Sessions struct {
	Expired time.Duration // 保存 session 时间长
	Name    string        // Cookie 名
	Size    int           // 会话 ID 长度
	Salt    string        // 加盐
	// contains filtered or unexported fields
}

Sessions 管理不同用户的会话。

注意:内部含 sync.WaitGroup 与 vmap.Map,**不可按值复制**。

配置字段:

  • Expired: 空闲过期时长(0 表示不过期)
  • Name: Cookie 名称,如 "VID"
  • Size: 会话 ID 字节长度(默认 64)
  • Salt: 可选加盐,增加伪随机熵

示例:

ss := &Sessions{Expired: 20 * time.Minute, Name: "VID", Size: 64}
sess := ss.Session(w, r) // 自动读 Cookie 或新建并 Set-Cookie

func (*Sessions) CheckDeadAll

func (T *Sessions) CheckDeadAll() []any

CheckDeadAll 定时检查并清理过期会话;返回被删除的 id 列表。 在 Range 内只标记,Range 外再 Free,避免用户 Defer 回调死锁。

func (*Sessions) Configure added in v3.5.0

func (T *Sessions) Configure(f func(*Sessions))

Configure 在写锁下更新配置(避免与 Get/Check 竞态)。

示例:ss.Configure(func(s *Sessions) { s.Expired = time.Hour })

func (*Sessions) DelSession

func (T *Sessions) DelSession(id string)

DelSession 删除指定 id 的会话并 Free。

func (*Sessions) GetSession

func (T *Sessions) GetSession(id string) (*Session, bool)

GetSession 使用 id 读取会话;过期则标记并异步 Free,返回 (nil, false)。 成功时会刷新 recent 时间戳。

func (*Sessions) InstantDeadAll

func (T *Sessions) InstantDeadAll()

InstantDeadAll 立即清理全部会话,并异步执行各自的 Defer。

func (*Sessions) InstantDeadAllInto added in v3.3.0

func (T *Sessions) InstantDeadAllInto(wg *sync.WaitGroup)

InstantDeadAllInto 与 InstantDeadAll 相同,但把每个异步 Free 注册到调用方 wg。 SitePool.Close 用此等待最多 3 秒。

func (*Sessions) Len

func (T *Sessions) Len() int

Len 当前会话数量。

func (*Sessions) NewSession

func (T *Sessions) NewSession(id string) *Session

NewSession 按 id 新建或返回已有会话。

func (*Sessions) Session

func (T *Sessions) Session(rw http.ResponseWriter, req *http.Request) Sessioner

Session 是面向 Handler 的便捷入口: 1. 请求 Cookie 有效 → 复用; 2. 响应头已有同名 Set-Cookie → 复用; 3. 否则新建随机会话并写入 Set-Cookie。

返回 Sessioner;Name 为空时返回 nil。

func (*Sessions) SessionID

func (T *Sessions) SessionID(req *http.Request) (id string, err error)

SessionID 从请求 Cookie 中读取会话标识。

返回:id 字符串,或错误(请求为空、Cookie 名未配置、客户端无该 Cookie)

func (*Sessions) SetSession

func (T *Sessions) SetSession(id string, s *Session) *Session

SetSession 写入会话;若同 id 已有不同 Token 的旧会话,则标记旧会话待 Free。

type Site

type Site struct {
	RootDir func(path string) string // 网站的根目录解析
	Extend  vmap.Map                 // 用户自定义扩展数据
	// contains filtered or unexported fields
}

Site 站点数据存储:会话集、全局 Map、根目录函数、扩展数据。

func (*Site) Global

func (T *Site) Global() Globaler

Global 返回站点全局数据接口。

func (*Site) PoolName

func (T *Site) PoolName() string

PoolName 返回站点在池中的名称(Identity)。

func (*Site) Sessions

func (T *Site) Sessions() *Sessions

Sessions 返回本站点的会话管理器。

type SiteMan

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

SiteMan 按 Host 管理 *Site 的映射,支持贬域名(通配符)匹配。

func (*SiteMan) Add

func (T *SiteMan) Add(host string, site *Site)

Add 设置一个站点;site==nil 时删除该 host。

func (*SiteMan) Get

func (T *SiteMan) Get(host string) (*Site, bool)

Get 读取站点;精确匹配失败时尝试贬域名(如 *.example.com)。

返回:(*Site, true) 或 (nil, false)

func (*SiteMan) Range

func (T *SiteMan) Range(f func(host string, site *Site) bool)

Range 遍历所有精确注册的站点。

type SitePool

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

SitePool 网站池:按名称管理多个 *Site,并定期回收过期会话。

生命周期:

sp := NewSitePool()
site := sp.NewSite("default")
// ... 使用 site.Sessions() / site.Global()
sp.Close() // 停止 ticker、清理会话与全局数据

func NewSitePool

func NewSitePool() *SitePool

NewSitePool 创建站点池并启动后台回收协程(默认每秒一次)。

func (*SitePool) Close

func (T *SitePool) Close() error

Close 关闭池:停止 ticker、清理全局/扩展数据、异步 Free 所有会话并等待最多 3 秒。 已关闭则返回 "SitePool is closed"。

func (*SitePool) DelSite

func (T *SitePool) DelSite(name string)

DelSite 从池中删除指定名称的站点(不主动 Free 会话,建议先 Close 或手动清理)。

func (*SitePool) NewSite

func (T *SitePool) NewSite(name string) *Site

NewSite 创建一个站点;若 name 已存在则返回已有实例。 Sessions 使用默认:Expired=20min, Name="VID", Size=64。

参数 name:站点标识(池内唯一) 返回:*Site(永不 nil)

示例:

site := pool.NewSite("blog")

func (*SitePool) RangeSite

func (T *SitePool) RangeSite(f func(name string, site *Site) bool)

RangeSite 遍历池中所有站点;f 返回 false 时停止。

示例:

pool.RangeSite(func(name string, site *Site) bool {
    fmt.Println(name, site.Sessions().Len())
    return true
})

func (*SitePool) SetRecoverSession

func (T *SitePool) SetRecoverSession(d time.Duration)

SetRecoverSession 设置回收无效会话的间隔。默认为 1 秒。 d <= 0 时强制为 1 秒,防止 ticker 高频空转打满 CPU。

Directories

Path Synopsis
cmd
main command

Jump to

Keyboard shortcuts

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