web

package module
v0.20.0 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2026 License: MIT Imports: 25 Imported by: 0

README

web

web 是 infrago 的模块

包定位

  • 类型:模块
  • 作用:Web 模块,负责站点、多路由、静态资源与业务整合。

主要功能

  • 对上提供统一模块接口
  • 对下通过驱动接口接入具体后端
  • 支持按配置切换驱动实现

快速接入

import _ "github.com/infrago/web"
[web]
driver = "default"

驱动实现接口列表

以下接口由驱动实现(来自模块 driver.go):

Driver
  • Connect(*Instance) (Connection, error)
Connection
  • Open() error
  • Close() error
  • Register(name string, info Info, hosts []string) error
  • Start() error
  • StartTLS(certFile, keyFile string) error
Delegate
  • Serve(name string, params Map, res http.ResponseWriter, req *http.Request)

站点跨域配置

跨域只支持站点级配置,不支持全局 [cross] / [web.cross]

  • [site.xxx.cross]
  • cross = { enable = true, ... }

常用键:

  • allow / enable
  • method / methods
  • origin / origins
  • header / headers

全局配置项(所有配置键)

配置段:[web]

  • driver
  • port
  • host
  • bind
  • cert
  • certfile
  • key
  • keyfile
  • charset
  • cookie
  • token
  • expire
  • crypto
  • maxage
  • httponly
  • answerencode
  • codec
  • answer
  • upload
  • static
  • shared
  • defaults
  • domain
  • domains
  • alias
  • aliases
  • setting

说明

  • setting 一般用于向具体驱动透传专用参数
  • 多实例配置请参考模块源码中的 Config/configure 处理逻辑

Documentation

Index

Constants

View Source
const (
	UTF8    = "utf-8"
	DEFAULT = "default"
)
View Source
const (
	StatusContinue           = http.StatusContinue
	StatusSwitchingProtocols = http.StatusSwitchingProtocols
	StatusProcessing         = http.StatusProcessing
	StatusEarlyHints         = http.StatusEarlyHints

	StatusOK                   = http.StatusOK
	StatusCreated              = http.StatusCreated
	StatusAccepted             = http.StatusAccepted
	StatusNonAuthoritativeInfo = http.StatusNonAuthoritativeInfo
	StatusNoContent            = http.StatusNoContent
	StatusResetContent         = http.StatusResetContent
	StatusPartialContent       = http.StatusPartialContent

	StatusMultipleChoices   = http.StatusMultipleChoices
	StatusMovedPermanently  = http.StatusMovedPermanently
	StatusFound             = http.StatusFound
	StatusSeeOther          = http.StatusSeeOther
	StatusNotModified       = http.StatusNotModified
	StatusUseProxy          = http.StatusUseProxy
	StatusTemporaryRedirect = http.StatusTemporaryRedirect
	StatusPermanentRedirect = http.StatusPermanentRedirect

	StatusBadRequest                   = http.StatusBadRequest
	StatusUnauthorized                 = http.StatusUnauthorized
	StatusPaymentRequired              = http.StatusPaymentRequired
	StatusForbidden                    = http.StatusForbidden
	StatusNotFound                     = http.StatusNotFound
	StatusMethodNotAllowed             = http.StatusMethodNotAllowed
	StatusNotAcceptable                = http.StatusNotAcceptable
	StatusProxyAuthRequired            = http.StatusProxyAuthRequired
	StatusRequestTimeout               = http.StatusRequestTimeout
	StatusConflict                     = http.StatusConflict
	StatusGone                         = http.StatusGone
	StatusLengthRequired               = http.StatusLengthRequired
	StatusPreconditionFailed           = http.StatusPreconditionFailed
	StatusRequestEntityTooLarge        = http.StatusRequestEntityTooLarge
	StatusRequestURITooLong            = http.StatusRequestURITooLong
	StatusUnsupportedMediaType         = http.StatusUnsupportedMediaType
	StatusRequestedRangeNotSatisfiable = http.StatusRequestedRangeNotSatisfiable
	StatusExpectationFailed            = http.StatusExpectationFailed
	StatusTeapot                       = http.StatusTeapot
	StatusMisdirectedRequest           = http.StatusMisdirectedRequest
	StatusUnprocessableEntity          = http.StatusUnprocessableEntity
	StatusLocked                       = http.StatusLocked
	StatusFailedDependency             = http.StatusFailedDependency
	StatusTooEarly                     = http.StatusTooEarly
	StatusUpgradeRequired              = http.StatusUpgradeRequired
	StatusPreconditionRequired         = http.StatusPreconditionRequired
	StatusTooManyRequests              = http.StatusTooManyRequests
	StatusRequestHeaderFieldsTooLarge  = http.StatusRequestHeaderFieldsTooLarge
	StatusUnavailableForLegalReasons   = http.StatusUnavailableForLegalReasons

	StatusInternalServerError           = http.StatusInternalServerError
	StatusNotImplemented                = http.StatusNotImplemented
	StatusBadGateway                    = http.StatusBadGateway
	StatusServiceUnavailable            = http.StatusServiceUnavailable
	StatusGatewayTimeout                = http.StatusGatewayTimeout
	StatusHTTPVersionNotSupported       = http.StatusHTTPVersionNotSupported
	StatusVariantAlsoNegotiates         = http.StatusVariantAlsoNegotiates
	StatusInsufficientStorage           = http.StatusInsufficientStorage
	StatusLoopDetected                  = http.StatusLoopDetected
	StatusNotExtended                   = http.StatusNotExtended
	StatusNetworkAuthenticationRequired = http.StatusNetworkAuthenticationRequired
)

Variables

This section is empty.

Functions

func RouteUri added in v0.11.0

func RouteUri(name string, values ...Map) string

RouteUri shortcut

func RouteUrl

func RouteUrl(name string, values ...Map) string

RouteUrl shortcut

func SetFS

func SetFS(fsys fs.FS)

func SiteUrl

func SiteUrl(name, path string, options ...Map) string

SiteUrl shortcut

func StatusText

func StatusText(code int) string

Types

type Config

type Config struct {
	Driver string
	Port   int
	Host   string

	CertFile string
	KeyFile  string

	Charset string

	Cookie   string
	Token    bool
	Expire   time.Duration
	Crypto   bool
	MaxAge   time.Duration
	HttpOnly bool
	// AnswerDataEncode toggles ctx.Answer(data) payload encoding.
	AnswerDataEncode bool
	// AnswerDataCodec is codec name used by infra.Mapping Var.Encode.
	AnswerDataCodec string

	Upload   string
	Static   string
	Shared   string
	Defaults []string

	Domain  string
	Domains []string
	Alias   string
	Aliases []string

	Setting Map
	// contains filtered or unexported fields
}

type Configs

type Configs map[string]Config

type Connection

type Connection interface {
	Open() error
	Close() error

	Register(name string, info Info, hosts []string) error
	Upgrade(res http.ResponseWriter, req *http.Request) (Socket, error)

	Start() error
	StartTLS(certFile, keyFile string) error
}

Connection defines web connection interface.

type Context

type Context struct {
	*infra.Meta

	Name    string
	Config  Router
	Setting Map

	Method     string
	Host       string
	Site       string
	Domain     string
	RootDomain string
	Path       string
	Uri        string

	Ajax bool

	Params Map
	Query  Map
	Form   Map
	Upload Map

	Value  Map
	Args   Map
	Locals Map

	Code int
	Type string
	Data Map
	Body Any
	// contains filtered or unexported fields
}

func (*Context) Agent

func (ctx *Context) Agent() string

func (*Context) Answer added in v0.11.1

func (ctx *Context) Answer(res Res, args ...Any)

Answer outputs API response.

func (*Context) Binary

func (ctx *Context) Binary(bytes []byte, args ...string)

func (*Context) Charset

func (ctx *Context) Charset(charsets ...string) string

func (*Context) Cookie

func (ctx *Context) Cookie(key string, vals ...Any) string

func (*Context) Deny added in v0.8.3

func (ctx *Context) Deny(args ...Res)

func (*Context) Error

func (ctx *Context) Error(args ...Res)

func (*Context) Fail added in v0.8.3

func (ctx *Context) Fail(args ...Res)

func (*Context) File

func (ctx *Context) File(file string, args ...string)

func (*Context) Goto

func (ctx *Context) Goto(url string)

func (*Context) HTML

func (ctx *Context) HTML(html Any, args ...Any)

func (*Context) Header

func (ctx *Context) Header(key string, vals ...string) string

func (*Context) IP

func (ctx *Context) IP() string

func (*Context) JSON

func (ctx *Context) JSON(json Any, args ...Any)

func (*Context) JSONP

func (ctx *Context) JSONP(callback string, json Any, args ...Any)

func (*Context) NewSign added in v0.9.0

func (ctx *Context) NewSign(auth bool, payload Map, expires ...time.Duration) string

NewSign issues token with new token id and marks cookie issuance. expires is optional duration, begin defaults to current time.

func (*Context) NewSignAt added in v0.9.0

func (ctx *Context) NewSignAt(auth bool, payload Map, begin time.Time, expires ...time.Duration) string

NewSignAt issues token with new token id and custom begin time. expires is optional duration.

func (*Context) Next

func (ctx *Context) Next()

func (*Context) NotFound added in v0.8.3

func (ctx *Context) NotFound()

func (*Context) Proxy added in v0.12.0

func (ctx *Context) Proxy(target string)

func (*Context) Redirect

func (ctx *Context) Redirect(url string)

func (*Context) RouteUri added in v0.11.0

func (ctx *Context) RouteUri(name string, values ...Map) string

func (*Context) RouteUrl added in v0.11.0

func (ctx *Context) RouteUrl(name string, values ...Map) string

func (*Context) Sign added in v0.9.0

func (ctx *Context) Sign(auth bool, payload Map, expires ...time.Duration) string

Sign issues token and marks cookie issuance. expires is optional duration, begin defaults to current time.

func (*Context) SignAt added in v0.9.0

func (ctx *Context) SignAt(auth bool, payload Map, begin time.Time, expires ...time.Duration) string

SignAt issues token with custom begin time and marks cookie issuance. expires is optional duration.

func (*Context) SiteUrl added in v0.11.0

func (ctx *Context) SiteUrl(name, path string, options ...Map) string

func (*Context) Status

func (ctx *Context) Status(code int, texts ...string)

func (*Context) Stream added in v0.12.0

func (ctx *Context) Stream(buffer io.ReadCloser, size int64, args ...string)

func (*Context) Text

func (ctx *Context) Text(text Any, args ...Any)

func (*Context) Unauth added in v0.8.3

func (ctx *Context) Unauth(args ...Res)

func (*Context) Unsign added in v0.8.3

func (ctx *Context) Unsign(args ...Res)

func (*Context) Upgrade added in v0.19.0

func (ctx *Context) Upgrade(spaces ...string) error

func (*Context) View added in v0.11.0

func (ctx *Context) View(view string, args ...Any)

View renders template by view module. args can include: int(status code), string(mime), Map(model).

type Cookie = http.Cookie

type Cross

type Cross struct {
	Allow   bool
	Method  string
	Methods []string
	Origin  string
	Origins []string
	Header  string
	Headers []string
}

type Delegate

type Delegate interface {
	Serve(name string, params Map, res http.ResponseWriter, req *http.Request)
}

Delegate handles web requests.

type Driver

type Driver interface {
	Connect(*Instance) (Connection, error)
}

Driver defines web driver interface.

type File

type File struct {
	Checksum  string `json:"checksum"`
	Filename  string `json:"filename"`
	Extension string `json:"extension"`
	Mimetype  string `json:"mimetype"`
	Length    int64  `json:"length"`
	Tempfile  string `json:"tempfile"`
}

File represents uploaded file info.

type Filter

type Filter struct {
	Name     string  `json:"name"`
	Desc     string  `json:"desc"`
	Serve    ctxFunc `json:"-"`
	Request  ctxFunc `json:"-"`
	Execute  ctxFunc `json:"-"`
	Response ctxFunc `json:"-"`
}

Filter defines HTTP filter/interceptor.

type Handler

type Handler struct {
	Name     string  `json:"name"`
	Desc     string  `json:"desc"`
	NotFound ctxFunc `json:"-"`
	Error    ctxFunc `json:"-"`
	Failed   ctxFunc `json:"-"`
	Unsigned ctxFunc `json:"-"`
	Unauthed ctxFunc `json:"-"`
	Denied   ctxFunc `json:"-"`
}

Handler defines HTTP handler for errors.

type Info

type Info struct {
	Method string
	Uri    string
	Router string
	Entry  string
	Args   Vars
}

Info contains route information.

type Instance

type Instance struct {
	Config   Config
	Setting  Map
	Delegate Delegate
	// contains filtered or unexported fields
}

type Loader added in v0.12.0

type Loader struct {
	Required bool   `json:"required"`
	Invoke   string `json:"invoke"`
	Value    string `json:"value"`
	Args     string `json:"args"`
	Name     string `json:"name"`
	Desc     string `json:"desc"`
	Empty    Res    `json:"-"`
	Error    Res    `json:"-"`
}

type Loading added in v0.12.0

type Loading map[string]Loader

type Module

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

func (*Module) Close

func (m *Module) Close()

func (*Module) Config

func (m *Module) Config(global Map)

Config parses global config for web.

func (*Module) Open

func (m *Module) Open()

func (*Module) Register

func (m *Module) Register(name string, value Any)

Register dispatches registrations.

func (*Module) RegisterConfig

func (m *Module) RegisterConfig(name string, config Config)

RegisterConfig registers web config for a named site.

func (*Module) RegisterConfigs

func (m *Module) RegisterConfigs(configs Configs)

RegisterConfigs registers multiple configs.

func (*Module) RegisterDriver

func (m *Module) RegisterDriver(name string, driver Driver)

RegisterDriver registers a web driver.

func (*Module) RegisterFilter

func (m *Module) RegisterFilter(name string, config Filter)

RegisterFilter registers a web filter.

func (*Module) RegisterHandler

func (m *Module) RegisterHandler(name string, config Handler)

RegisterHandler registers a web handler.

func (*Module) RegisterRouter

func (m *Module) RegisterRouter(name string, config Router)

RegisterRouter registers a web router.

func (*Module) RegisterRouters

func (m *Module) RegisterRouters(prefix string, routers Routers)

RegisterRouters registers multiple routers.

func (*Module) Serve

func (m *Module) Serve(name string, params Map, res http.ResponseWriter, req *http.Request)

Serve implements Delegate to dispatch by host/site.

func (*Module) Setup

func (m *Module) Setup()

Setup initializes defaults and sites.

func (*Module) Start

func (m *Module) Start()

func (*Module) Stop

func (m *Module) Stop()

type Router

type Router struct {
	Uri      string   `json:"uri"`
	Uris     []string `json:"uris"`
	Key      string   `json:"-"`
	Name     string   `json:"name"`
	Desc     string   `json:"desc"`
	Nullable bool     `json:"-"`
	Args     Vars     `json:"args"`
	Data     Vars     `json:"data"`
	Setting  Map      `json:"-"`
	Loading  Loading  `json:"loading"`

	Routing Routing   `json:"routing"`
	Actions []ctxFunc `json:"-"`
	Action  ctxFunc   `json:"-"`

	Sign bool `json:"sign"`
	Auth bool `json:"auth"`

	NotFound ctxFunc `json:"-"`
	Error    ctxFunc `json:"-"`
	Failed   ctxFunc `json:"-"`
	Unsigned ctxFunc `json:"-"`
	Unauthed ctxFunc `json:"-"`
	Denied   ctxFunc `json:"-"`
	// contains filtered or unexported fields
}

Router defines HTTP route.

func (Router) RegistryComponent

func (Router) RegistryComponent() string

type Routers

type Routers map[string]Router

Routers defines batch router registration.

func (Routers) RegistryComponent

func (Routers) RegistryComponent() string

type Routing

type Routing map[string]Router

type Site

type Site Config

func (Site) RegistryComponent added in v0.11.1

func (Site) RegistryComponent() string

type Sites added in v0.11.1

type Sites map[string]Site

func (Sites) RegistryComponent added in v0.11.1

func (Sites) RegistryComponent() string

type Socket added in v0.19.0

type Socket interface {
	ReadMessage() (int, []byte, error)
	WriteMessage(messageType int, data []byte) error
	Close() error
	Raw() Any
}

Jump to

Keyboard shortcuts

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