router

package
v0.0.0-...-5e9c659 Latest Latest
Warning

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

Go to latest
Published: Jan 20, 2024 License: Apache-2.0 Imports: 38 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MODULE_DIR   = "module" // # 模块文件夹名称
	STATIC_DIR   = "static"
	TEMPLATE_DIR = "template"
)
View Source
const (
	// type of handler
	LocalHandler HandlerType = iota
	ProxyHandler
	SubscriberHandler

	HttpHandler TransportType = iota
	RpcHandler
	SubscribeHandler
	ReflectHandler // TODO废弃
)
View Source
const (
	StaticNode  NodeType = iota // static, should equal
	VariantNode                 // named node, match a non-/ is ok
	AnyNode                     // catch-all node, match any
	RegexpNode                  // regex node, should match

	AllType ContentType = iota
	NumberType
	CharType

	LBracket = '<'
	RBracket = '>'
)

tree 负责路由树的解析,排序,匹配 实现前面加类型 '/web/content/<string:xmlid>', '/web/content/<string:xmlid>/<string:filename>', '/web/content/<int:id>', '/web/content/<int:id>/<string:filename>', '/web/content/<int:id>-<string:unique>', '/web/content/<int:id>-<string:unique>/<string:filename>', '/web/content/<string:model>/<int:id>/<string:field>', '/web/content/<string:model>/<int:id>/<string:field>/<string:filename>'

View Source
const (
	// DefaultPrefix url prefix of pprof
	DefaultPrefix = "/debug/pprof"
)

Variables

View Source
var (
	HttpContext     = "HttpContext"                   // 标识用于判断String()
	HttpContextType = reflect.TypeOf(&THttpContext{}) // must be a pointer

)
View Source
var (
	RpcContextType = reflect.TypeOf(&TRpcContext{}) // must be a pointer
	RpcContext     = "RpcContext"                   // 标识用于判断String()
)
View Source
var ContextType = reflect.TypeOf(new(IContext)).Elem()
View Source
var (
	ControllerMethodNameMapper = func(name string) string {
		name = strings.ToLower(name)

		name = strings.Replace(name, "api_", "", 1)
		return name
	}
)

Functions

func EndpiontToRoute

func EndpiontToRoute(ep *registry.Endpoint) *route

func GetFuncName

func GetFuncName(i interface{}, seps ...rune) string

func GetModulePath

func GetModulePath(module string, downloaded bool, display_warning bool) (res string)
"""Return the path of the given module.

Search the addons paths and return the first path where the given module is found. If downloaded is True, return the default addons path if nothing else is found.

"""

func GetResourcePath

func GetResourcePath(module_src_path string) (res string)

func HttpReverseProxy

func HttpReverseProxy(ctx *THttpContext)

TODO 改名称

func Logger

func Logger() logger.ILogger

func RouteToEndpiont

func RouteToEndpiont(r *route) *registry.Endpoint

func RpcReverseProxy

func RpcReverseProxy(ctx *TRpcContext)

TODO 改名称

func Validate

func Validate(e *registry.Endpoint) error

TODO Validate validates an endpoint to guarantee it won't blow up when being served

func WithNameMapper

func WithNameMapper(fn func(string) string) config.Option

func WrapFn

func WrapFn(fn http.HandlerFunc) func(*THttpContext)

WrapFn is a helper function for wrapping http.HandlerFunc and returns a HttpContext.

func WrapHd

func WrapHd(h http.Handler) func(*THttpContext)

WrapH is a helper function for wrapping http.Handler and returns a HttpContext.

func WrapHttp

func WrapHttp(fn func(IContext)) func(*THttpContext)

func WrapRpc

func WrapRpc(fn func(IContext)) func(*TRpcContext)

Types

type BufferPool

type BufferPool interface {
	Get() []byte
	Put([]byte)
}

A BufferPool is an interface for getting and returning temporary byte slices for use by io.CopyBuffer.

type Config

type Config struct {
	config.Config  `field:"-"`
	Name           string             `field:"-"` // config name/path in config file
	PrefixName     string             `field:"-"` // config prefix name
	Logger         logger.ILogger     `field:"-"` // 实例
	Router         *TRouter           `field:"-"`
	Registry       registry.IRegistry `field:"-"`
	RegistryCacher cacher.ICacher     `field:"-"` // registry cache

	// mapping to config file
	RecoverHandler    func(IContext) `field:"-"`
	Recover           bool           `field:"recover"`
	RouterTreePrinter bool           `field:"router_tree_printer"`
	RequestPrinter    bool           `field:"request_printer"`
	StaticDir         []string       `field:"static_dir"` // the static dir allow to visit
	StaticExt         []string       `field:"static_ext"` // the static file format allow to visit
	UsePprof          bool
	UploadBuf         int `field:"upload_buf"` // 上传文件大小MB
}

func (*Config) Init

func (self *Config) Init(opts ...Option)

func (*Config) Load

func (self *Config) Load() error

func (*Config) Save

func (self *Config) Save(immed ...bool) error

func (*Config) String

func (self *Config) String() string

type ConfigOption

type ConfigOption func(*TTree)

配置函数接口

func WithIgnoreCase

func WithIgnoreCase() ConfigOption

忽略大小写

type ContentType

type ContentType byte // 变量类型

func (ContentType) String

func (self ContentType) String() string

type ControllerConfig

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

控制器配置 可实现特殊功能 功能:中间件过滤器

func (*ControllerConfig) AddFilter

func (self *ControllerConfig) AddFilter(middleware string, handlers ...string)

add which middleware name blocked handler name

type GroupConfig

type GroupConfig struct {
	Name string // 当前源代码文件夹名称

	FilePath      string // 当前源代码文件夹路径
	IsService     bool   // 是否在registry注册为独立的服务
	PathPrefix    string
	StaticHandler func(IContext) `field:"-"`
	// contains filtered or unexported fields
}

type GroupOption

type GroupOption func(*GroupConfig)

func WithAloneService

func WithAloneService(asService bool, servicsName string, prefix ...string) GroupOption

独立出来注册为单一微服务在registry里

func WithCurrentModulePath

func WithCurrentModulePath() GroupOption

func WithGroupName

func WithGroupName(name string) GroupOption

func WithGroupPathPrefix

func WithGroupPathPrefix(prefixPath string) GroupOption

TODO 更名 default url"/abc" PrefixPath url "/PrefixPath/abc"

func WithStaticHandler

func WithStaticHandler(handler func(IContext)) GroupOption

type HandlerType

type HandlerType byte

func (HandlerType) String

func (self HandlerType) String() string

type IContext

type IContext interface {

	// public
	Next()
	Body() *body.TBody
	Data() *TParamsSet
	PathParams() *TParamsSet
	Write([]byte) (int, error)
	WriteStream(interface{}) error
	Route() route
	Router() IRouter
	Context() context.Context
	RespondByJson(data interface{})
	HandlerIndex() int
	Handler(index ...int) *handler
	ValueModel() reflect.Value //
	TypeModel() reflect.Type
	IsDone() bool //response data is done
	String() string
	//Abort(string)
	NotFound(message ...string)
	// contains filtered or unexported methods
}

type IGroup

type IGroup interface {
	String() string
	// 返回Module所有Routes 理论上只需被调用一次
	GetRoutes() *TTree
	GetSubscribers() map[ISubscriber][]broker.ISubscriber
	GetPath() string
	GetFilePath() string
	GetTemplateVar() map[string]interface{}
	IsService() bool
}

非volts通用接口

type IMiddleware

type IMiddleware interface {
	Handler(ctx IContext)
}

中间件接口

type IMiddlewareName

type IMiddlewareName interface {
	Name() string
}

中间件名称接口

type IMiddlewareRest

type IMiddlewareRest interface {
	Rest()
}

中间件重置接口 重置接口用于实现特定成员手动清空 NOTE:改函数被调用有当Handler执行完毕并回收中

type IRouter

type IRouter interface {
	Config() *Config // Retrieve the options
	String() string
	Handler() interface{} // 连接入口 serveHTTP 等接口实现
	// Register endpoint in router
	Register(ep *registry.Endpoint) error
	// Deregister endpoint from router
	Deregister(ep *registry.Endpoint) error
	// list all endpiont from router
	Endpoints() (services map[*TGroup][]*registry.Endpoint)
	RegisterMiddleware(middlewares ...func(IRouter) IMiddleware)
	RegisterGroup(groups ...IGroup)
	PrintRoutes()
}

Router handle serving messages

type IString

type IString interface {
	String() string
}

type ISubscriber

type ISubscriber interface {
	Topic() string
	Subscriber() interface{} // 原型
	Endpoints() []*registry.Endpoint
	Handlers() []*handler
	Config() SubscriberConfig
}

Subscriber interface represents a subscription to a given topic using a specific subscriber function or object with endpoints. It mirrors the handler in its behavior.

type NodeType

type NodeType byte // 节点类型

func (NodeType) String

func (self NodeType) String() string

type Option

type Option func(*Config)

func Debug

func Debug() Option

func WithConfigPrefixName

func WithConfigPrefixName(prefixName string) Option

修改Config.json的路径

func WithPprof

func WithPprof() Option

func WithRecover

func WithRecover(on bool) Option

func WithRecoverHandler

func WithRecoverHandler(handler func(IContext)) Option

func WithRegistry

func WithRegistry(r registry.IRegistry) Option

func WithRequestPrinter

func WithRequestPrinter() Option

Register the service with a TTL

func WithRoutesTreePrinter

func WithRoutesTreePrinter() Option

Register the service with a TTL

type Params

type Params []param

func (*Params) Get

func (p *Params) Get(key string) string

func (*Params) Set

func (p *Params) Set(key, value string)

func (*Params) SetParams

func (p *Params) SetParams(params []param)

type RoutePosition

type RoutePosition byte
const (
	Normal RoutePosition = iota
	Before
	After
	Replace // the route replace origin
)

func (RoutePosition) String

func (self RoutePosition) String() string

type SubscriberConfig

type SubscriberConfig struct {
	Context context.Context
	Queue   string
	// AutoAck defaults to true. When a handler returns
	// with a nil error the message is acked.
	AutoAck  bool
	Internal bool
}

type SubscriberOption

type SubscriberOption func(*SubscriberConfig)

type TGroup

type TGroup struct {
	sync.RWMutex
	*TemplateVar

	Metadata map[string]string // 存储Group数据
	// contains filtered or unexported fields
}

服务模块 每个服务代表一个对象

func NewGroup

func NewGroup(opts ...GroupOption) *TGroup

new a module default url path :/{mod_name} default file path :/{mod_name}/{static}/ default tmpl path :/{mod_name{/{tmpl}/

func (*TGroup) Config

func (self *TGroup) Config() *GroupConfig

func (*TGroup) GetFilePath

func (self *TGroup) GetFilePath() string

获取组的绝对路径

func (*TGroup) GetPath

func (self *TGroup) GetPath() string

the URL path

func (*TGroup) GetRoutes

func (self *TGroup) GetRoutes() *TTree

func (*TGroup) GetSubscribers

func (self *TGroup) GetSubscribers() map[ISubscriber][]broker.ISubscriber

func (*TGroup) IsService

func (self *TGroup) IsService() bool

func (*TGroup) Name

func (self *TGroup) Name() string

func (*TGroup) NewSubscriber

func (h *TGroup) NewSubscriber(topic string, handler interface{}, opts ...SubscriberOption) ISubscriber

新建订阅对象

func (*TGroup) SetFilePath

func (self *TGroup) SetFilePath(path string)

func (*TGroup) SetPath

func (self *TGroup) SetPath(path string)

获取组的链接路径

func (*TGroup) SetStatic

func (self *TGroup) SetStatic(relativePath string, root ...string)

Static serves files from the given file system root. Internally a http.FileServer is used, therefore http.NotFound is used instead of the Router's NotFound handler. To use the operating system's file system implementation, use :

router.Static("/static", "/var/www")

func (*TGroup) StaticFile

func (self *TGroup) StaticFile(relativePath, filepath string)

StaticFile registers a single route in order to serve a single file of the local filesystem. router.StaticFile("favicon.ico", "./resources/favicon.ico")

func (*TGroup) String

func (self *TGroup) String() string

func (*TGroup) Subscribe

func (self *TGroup) Subscribe(subscriber ISubscriber) error

订阅对象

func (*TGroup) Url

func (self *TGroup) Url(method string, path string, handlers ...any) *route

!NOTE! RPC 或者 HTTP 不适用同一Module注册路由

Add route with method HTTP: "GET/POST/DELETE/PUT/HEAD/OPTIONS/REST" RPC: "CONNECT"

Match rules Base: <type:name> if difine type than the route only match the string same to the type Example:

<string:id> 	only match "abc"
   <int:id> 	only match number "123"
      <:id> 	could match all kind of type with name id

'//' -- 生成"/abc/"而非"/abc"
'/web/<string:id>',
'/web/<string:id>/<string:name>',
'/web/<int:id>',
'/web/<int:id>/<string:name>',
'/web/<int:id>-<string:unique>',
'/web/<int:id>-<string:unique>/<string:name>',
'/web/<string:model>/<int:id>/<string:field>',
'/web/<string:model>/<int:id>/<string:field>/<string:name>'
'/web/*'

for details please read tree.go

@handlers 第一个将会被用于主要控制器其他将被归为中间件 @method:

API:会映射所有对象符合要求的控制器作为API发布
REST:会映射所有对象符合要求的create, read, update, and delete控制器作为Restful发布

type THttpContext

type THttpContext struct {
	logger.ILogger
	http.ResponseWriter

	// 模板
	TemplateVar
	Template    *template.TTemplateSet // 概念改进  为Hd添加 hd.Template.Params.Set("模板数据",Val)/Get()/Del()
	TemplateSrc string                 // 模板名称

	// 返回
	ContentType string
	Result      []byte // -- 最终返回数据由Apply提交
	// contains filtered or unexported fields
}

THttpContext 负责所有请求任务,每个Handle表示有一个请求

func NewHttpContext

func NewHttpContext(router *TRouter) *THttpContext

func (*THttpContext) Abort

func (self *THttpContext) Abort(body string, code ...int)

func (*THttpContext) Apply

func (self *THttpContext) Apply()

apply all changed to data

func (*THttpContext) Body

func (self *THttpContext) Body() *body.TBody

func (*THttpContext) Context

func (self *THttpContext) Context() context.Context

func (*THttpContext) Data

func (self *THttpContext) Data() *TParamsSet

数据缓存供传递用

func (*THttpContext) DelTemplateVar

func (self *THttpContext) DelTemplateVar(key string)

remove the var from the template

func (*THttpContext) Download

func (self *THttpContext) Download(file_path string) error

return a download file redirection for client

func (*THttpContext) GetCookie

func (self *THttpContext) GetCookie(name, key string) (value string, err error)

func (*THttpContext) GetTemplateVar

func (self *THttpContext) GetTemplateVar() map[string]interface{}

func (*THttpContext) Handler

func (self *THttpContext) Handler(index ...int) *handler

func (*THttpContext) HandlerIndex

func (self *THttpContext) HandlerIndex() int

func (*THttpContext) IP

func (self *THttpContext) IP() (res []string)

func (*THttpContext) IsDone

func (self *THttpContext) IsDone() bool

func (*THttpContext) MethodParams

func (self *THttpContext) MethodParams(blank ...bool) *TParamsSet

TODO 添加验证Request 防止多次解析

func (*THttpContext) Next

func (self *THttpContext) Next()

func (*THttpContext) NotFound

func (self *THttpContext) NotFound(message ...string)

Responds with 404 Not Found

func (*THttpContext) NotModified

func (self *THttpContext) NotModified()

func (*THttpContext) PathParams

func (self *THttpContext) PathParams() *TParamsSet

TODO 改为Route Params 如果返回 nil 代表 Url 不含改属性

func (*THttpContext) Redirect

func (self *THttpContext) Redirect(urlStr string, status ...int)

Ck

func (*THttpContext) RemoteAddr

func (self *THttpContext) RemoteAddr() string

RemoteAddr returns more real IP address of visitor.

func (*THttpContext) RenderTemplate

func (self *THttpContext) RenderTemplate(tmpl string, args interface{})

TODO 自定义文件夹 render the template and return to the end

func (*THttpContext) Request

func (self *THttpContext) Request() *transport.THttpRequest

func (*THttpContext) Respond

func (self *THttpContext) Respond(content []byte)

func (*THttpContext) RespondByJson

func (self *THttpContext) RespondByJson(data interface{})

NOTE default EscapeHTML=false Respond content by Json mode

func (*THttpContext) RespondError

func (self *THttpContext) RespondError(error string)

func (*THttpContext) Response

func (self *THttpContext) Response() *transport.THttpResponse

func (*THttpContext) Route

func (self *THttpContext) Route() route

func (*THttpContext) Router

func (self *THttpContext) Router() IRouter

func (*THttpContext) ServeFile

func (self *THttpContext) ServeFile(file_path string)

func (*THttpContext) SetCookie

func (self *THttpContext) SetCookie(name string, value string, others ...interface{})

SetCookie Sets the header entries associated with key to the single element value. It replaces any existing values associated with key. 一个cookie 有名称,内容,原始值,域,大小,过期时间,安全 cookie[0] => name string cookie[1] => value string cookie[2] => expires string cookie[3] => path string cookie[4] => domain string

func (*THttpContext) SetHeader

func (self *THttpContext) SetHeader(unique bool, hdr string, val string)

set the header of response

func (*THttpContext) SetTemplateVar

func (self *THttpContext) SetTemplateVar(key string, value interface{})

set the var of the template

func (*THttpContext) String

func (self *THttpContext) String() string

func (*THttpContext) TypeModel

func (self *THttpContext) TypeModel() reflect.Type

the reflect model of Type

func (*THttpContext) ValueModel

func (self *THttpContext) ValueModel() reflect.Value

the reflect model of Value

func (*THttpContext) Write

func (self *THttpContext) Write(data []byte) (int, error)

func (*THttpContext) WriteStream

func (self *THttpContext) WriteStream(data interface{}) error

type TMiddlewareManager

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

func (*TMiddlewareManager) Add

func (self *TMiddlewareManager) Add(key string, value func(IRouter) IMiddleware)

func (*TMiddlewareManager) Contain

func (self *TMiddlewareManager) Contain(key string) bool

func (*TMiddlewareManager) Del

func (self *TMiddlewareManager) Del(key string)

func (*TMiddlewareManager) Get

func (self *TMiddlewareManager) Get(key string) func(IRouter) IMiddleware

func (*TMiddlewareManager) Names

func (self *TMiddlewareManager) Names() []string

有序返回所有中间件名称 顺序依据注册顺序

func (*TMiddlewareManager) Set

func (self *TMiddlewareManager) Set(key string, value func(IRouter) IMiddleware)

type TParamsSet

type TParamsSet struct {
	dataset.TRecordSet
	// contains filtered or unexported fields
}

func NewParamsSet

func NewParamsSet(hd IContext) *TParamsSet

type TRouter

type TRouter struct {
	sync.RWMutex
	// router is a group set
	TGroup
	// contains filtered or unexported fields
}

router represents an RPC router.

func New

func New(opts ...Option) *TRouter

新建路由 NOTE 路由不支持线程安全 不推荐多服务器调用!

func (*TRouter) Config

func (self *TRouter) Config() *Config

func (*TRouter) Deregister

func (self *TRouter) Deregister(ep *registry.Endpoint) error

func (*TRouter) Endpoints

func (self *TRouter) Endpoints() (services map[*TGroup][]*registry.Endpoint)

func (*TRouter) Handler

func (self *TRouter) Handler() interface{}

func (*TRouter) PrintRoutes

func (self *TRouter) PrintRoutes()

func (*TRouter) Register

func (self *TRouter) Register(ep *registry.Endpoint) error

registry a endpoion to router

func (*TRouter) RegisterGroup

func (self *TRouter) RegisterGroup(groups ...IGroup)

register module

func (*TRouter) RegisterMiddleware

func (self *TRouter) RegisterMiddleware(middlewares ...func(IRouter) IMiddleware)

注册中间件

func (*TRouter) ServeHTTP

func (self *TRouter) ServeHTTP(w http.ResponseWriter, r *transport.THttpRequest)

func (*TRouter) ServeRPC

func (self *TRouter) ServeRPC(w *transport.RpcResponse, r *transport.RpcRequest)

func (*TRouter) String

func (self *TRouter) String() string

type TRpcContext

type TRpcContext struct {
	logger.ILogger
	// contains filtered or unexported fields
}

代表一个控制集

func NewRpcHandler

func NewRpcHandler(router *TRouter) *TRpcContext

func (*TRpcContext) Abort

func (self *TRpcContext) Abort(message ...string)

func (*TRpcContext) Body

func (self *TRpcContext) Body() *body.TBody

func (*TRpcContext) Context

func (self *TRpcContext) Context() context.Context

func (*TRpcContext) Data

func (self *TRpcContext) Data() *TParamsSet

func (*TRpcContext) Forbidden

func (self *TRpcContext) Forbidden(message ...string)

func (*TRpcContext) Handler

func (self *TRpcContext) Handler(index ...int) *handler

func (*TRpcContext) HandlerIndex

func (self *TRpcContext) HandlerIndex() int

func (*TRpcContext) IsDone

func (self *TRpcContext) IsDone() bool

func (*TRpcContext) Next

func (self *TRpcContext) Next()

func (*TRpcContext) NotFound

func (self *TRpcContext) NotFound(message ...string)

func (*TRpcContext) PathParams

func (self *TRpcContext) PathParams() *TParamsSet

func (*TRpcContext) Request

func (self *TRpcContext) Request() *transport.RpcRequest

func (*TRpcContext) RespondByJson

func (self *TRpcContext) RespondByJson(data interface{})

func (*TRpcContext) Response

func (self *TRpcContext) Response() *transport.RpcResponse

func (*TRpcContext) Route

func (self *TRpcContext) Route() route

func (*TRpcContext) Router

func (self *TRpcContext) Router() IRouter

func (*TRpcContext) String

func (self *TRpcContext) String() string

func (*TRpcContext) TypeModel

func (self *TRpcContext) TypeModel() reflect.Type

the reflect model of Type

func (*TRpcContext) ValueModel

func (self *TRpcContext) ValueModel() reflect.Value

the reflect model of Value

func (*TRpcContext) Write

func (self *TRpcContext) Write(data []byte) (int, error)

func (*TRpcContext) WriteStream

func (self *TRpcContext) WriteStream(data interface{}) error

func (*TRpcContext) WriteStreamWithCodec

func (self *TRpcContext) WriteStreamWithCodec(data interface{}, c codec.ICodec) error

type TSubscriberContext

type TSubscriberContext struct {
}

type TTree

type TTree struct {
	sync.RWMutex // lock for conbine action

	Text       string
	IgnoreCase bool

	PrefixChar byte // the Prefix Char </>xxx.xxx
	Count      atomic.Int32
	// contains filtered or unexported fields
}

safely tree

func NewRouteTree

func NewRouteTree(opts ...ConfigOption) *TTree

func (*TTree) AddRoute

func (self *TTree) AddRoute(route *route) error

添加路由到Tree

func (*TTree) Conbine

func (self *TTree) Conbine(from *TTree) *TTree

conbine 2 tree together

func (*TTree) DelRoute

func (self *TTree) DelRoute(path string, route *route) error

delete the route

func (*TTree) Endpoints

func (self *TTree) Endpoints() (services map[*TGroup][]*registry.Endpoint)

func (*TTree) Init

func (self *TTree) Init(opts ...ConfigOption)

func (*TTree) Match

func (r *TTree) Match(method string, path string) (*route, Params)

func (*TTree) PrintTrees

func (self *TTree) PrintTrees()

type TUrl

type TUrl struct {
	Scheme     string
	Opaque     string // encoded opaque data
	Host       string // host or host:port
	Path       string // path (relative paths may omit leading slash)
	Controller string
	Action     string
}

[scheme:][//[userinfo@]host][/path/controller.action][?query][#fragment]

type TemplateVar

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

func (*TemplateVar) DelTemplateVar

func (self *TemplateVar) DelTemplateVar(key string)

remove the var from the template

func (*TemplateVar) GetTemplateVar

func (self *TemplateVar) GetTemplateVar() map[string]interface{}

func (*TemplateVar) SetTemplateVar

func (self *TemplateVar) SetTemplateVar(key string, value interface{})

set the var of the template

type TransportType

type TransportType byte

Directories

Path Synopsis
middleware

Jump to

Keyboard shortcuts

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