vweb

package module
v3.0.7 Latest Latest
Warning

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

Go to latest
Published: Jun 29, 2026 License: Apache-2.0 Imports: 37 Imported by: 1

README

vweb Build Status

golang vweb, 简单的web服务器。

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	SiteContextKey     = &contextKey{"web-site"}
	RouterContextKey   = &contextKey{"web-router"}
	ListenerContextKey = &contextKey{"web-listener"}
	ConnContextKey     = &contextKey{"web-conn"}
	PluginContextKey   = &contextKey{"web-plugin"}
)

上下文中使用的key

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 // 响应
}

func (*Cookie) Add

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

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

name string         	名称
value string        	值
path string         	路径
domain string       	域
maxAge int          	过期时间,以毫秒为单位
secure bool         	源,如果通过 SSL 连接 (HTTPS) 传输 Cookie,则为 true;否则为 false。默认值为 false。
only bool           	验证,如果 Cookie 具有 HttpOnly 属性且不能通过客户端脚本(JS)访问,则为 true;否则为 false。默认为 false。
sameSite http.SameSite	是否严格模式

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)                                                                             // 删除
}

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 保存为静态文件

path string	保存路径

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) // 替换上下文
}

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

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
}

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

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 预编译正则,建议在程序初始化或配置加载时调用一次

type ForwardRewriter

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

ForwardRewriter 编译后的执行对象

func (*ForwardRewriter) Rewrite

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

type Globaler

type Globaler interface {
	Set(key, val any)                                     // 设置
	Has(key any) bool                                     // 检查
	Get(key any) any                                      // 读取
	Del(key any)                                          // 删除
	SetExpired(key any, d time.Duration)                  // 设置KEY有效期,过期会自动删除
	SetExpiredCall(key any, d time.Duration, f func(any)) // 设置KEY有效期,过期会自动删除,并调用函数
	Reset()                                               // 重置
}

type HandleFunc

type HandleFunc []func(Doter)

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
}

PluginHTTPClient 插件HTTP客户端

func (*PluginHTTPClient) Connection

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

Connection 快速连接HTTP

PluginHTTP	插件HTTP
error		错误

type PluginRPC

type PluginRPC interface {
	Type() PluginType                       // 类型
	Register(value any)                     // 注册struct类型
	Call(name string, arg any) (any, error) // 调用
	Discard() error                         // 废弃连接
	Close() error                           // 关闭
}

PluginRPC rpc插件接口

type PluginRPCClient

type PluginRPCClient struct {
	ConnPool *vconnpool.Pool // 连接池
	Addr     string          // 地址
	Path     string          // 路径
}

PluginRPCClient 插件RPC客户端

func (*PluginRPCClient) Connection

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

Connection 快速连接RPC

PluginRPC			插件RPC
error				错误

type PluginType

type PluginType int
const (
	PluginTypeRPC PluginType = iota
	PluginTypeHTTP
)

type Pluginer

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

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)     // 劫持,能双向互相发送信息
}

type Route

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

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))

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 string // 根目录
	PagePath string // 主模板文件路径

	// 可选的
	Site   *Site                                       // 网站配置
	Module func(name string) (DynamicTemplater, error) // 支持更动态文件类型

	SaveStatic func(filePath string, r io.Reader, l int) (int, error)          // 静态结果。仅在 .ServeHTTP 方法中使用
	ReadFile   func(filePath string, u *url.URL) (io.Reader, time.Time, error) // 读取文件。仅在 .ServeHTTP 方法中使用
	// contains filtered or unexported fields
}

ServerHandlerDynamic 处理动态页面文件

func (*ServerHandlerDynamic) Close added in v3.0.5

func (T *ServerHandlerDynamic) Close() error

func (*ServerHandlerDynamic) ServeHTTP

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

ServeHTTP 服务HTTP

rw http.ResponseWriter    响应
req *http.Request         请求

type ServerHandlerStatic

type ServerHandlerStatic struct {
	RootPath, PagePath string // 根目录, 页路径
	PageExpired        int64  // 页面过期时间(秒为单位)
	// contains filtered or unexported fields
}

ServerHandlerStatic 处理静态页面文件

func (*ServerHandlerStatic) ServeHTTP

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

ServeHTTP 服务HTTP

rw http.ResponseWriter    响应
req *http.Request         请求

type Session

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

Session 会话用于用户保存数据

func (*Session) Defer

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

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

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

func (*Session) Free

func (T *Session) Free()

Free 执行结束Defer和键值有效期

func (*Session) Token

func (T *Session) Token() string

Token 读取当前的令牌

string	令牌

type Sessioner

type Sessioner interface {
	Token() string                                        // 编号
	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)) // 过期调用
	Reset()                                               // 重置
	Defer(call any, args ...any) error                    // 退出调用
	Free()                                                // 释放调用
}

Sessioner 用户独立的内存存储接口

type Sessions

type Sessions struct {
	Expired      time.Duration // 保存session时间长
	Name         string        // 标识名称。用于Cookie
	Size         int           // 会话ID长度。用于Cookie
	Salt         string        // 加盐,由于计算机随机数是伪随机数。(可默认为空)。用于Cookie
	ActivationID bool          // 为true,保持会话ID。意思就是会话ID过期了,可以激活再次使用。用于Cookie
	// contains filtered or unexported fields
}

Sessions 用于管理不同用户的会话。

func (*Sessions) CheckDeadAll

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

CheckDeadAll 定时来处理过期的Session

[]string	过期的ID名称

func (*Sessions) DelSession

func (T *Sessions) DelSession(id string)

DelSession 使用id删除的会话

id string   id标识符

func (*Sessions) GetSession

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

GetSession 使用id读取会话

id string   id标识符
Sessioner   会话
bool        是否存在

func (*Sessions) InstantDeadAll

func (T *Sessions) InstantDeadAll()

func (*Sessions) Len

func (T *Sessions) Len() int

Len 当前Session数量

int	数量

func (*Sessions) NewSession

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

NewSession 新建会话

id string	id标识符
Sessioner   会话

func (*Sessions) Session

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

Session 会话

rw http.ResponseWriter  响应
req *http.Request       请求
Sessioner               会话接口

func (*Sessions) SessionID

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

SessionID 从请求中读取会话标识

req *http.Request   请求
id string           id标识符
err error           错误

func (*Sessions) SetSession

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

SetSession 使用id写入新的会话

id string   id标识符
s Sessioner 新的会话
Sessioner   会话

type Site

type Site struct {
	RootDir func(path string) string // 网站的根目录z
	Extend  vmap.Map                 // 接口类型,可以自己存在任何类型
	// contains filtered or unexported fields
}

Site 站点数据存储

func (*Site) Global

func (T *Site) Global() Globaler

func (*Site) PoolName

func (T *Site) PoolName() string

PoolName 网站池名称

string	名称

func (*Site) Sessions

func (T *Site) Sessions() *Sessions

type SiteMan

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

func (*SiteMan) Add

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

Add 设置一个站点

host string		站点host
*Site			站点

func (*SiteMan) Get

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

Get 读取一个站点

host string		站点host
*Site			站点
bool			true存在,否则没有

func (*SiteMan) Range

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

Range 迭举站点

f func(host string, site *Site) bool

type SitePool

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

SitePool 网站池

func NewSitePool

func NewSitePool() *SitePool

func (*SitePool) Close

func (T *SitePool) Close() error

Close 关闭池,关闭前将遍历池中的站点出来清理会话和全局数据。如果已经关闭则返回错误。

error   错误

func (*SitePool) DelSite

func (T *SitePool) DelSite(name string)

DelSite 删除站点

name string		站点name

func (*SitePool) NewSite

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

NewSite 创建一个站点,如果存在返回已经存在的。Sessions 使用默认的设置,你需要修改它。

name string		站点name
*Site			站点

func (*SitePool) RangeSite

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

RangeSite 迭举站点

f func(name string, site *Site) bool

func (*SitePool) SetRecoverSession

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

SetRecoverSession 设置回收无效的会话间隔。默认为1秒

d time.Duration     回收时间隔,不可以等于或小于0,否则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