protoweb

package module
v0.0.104 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2020 License: MIT Imports: 28 Imported by: 0

README

package gweb

实现目标

  • 兼容github.com/gin-gonic/gin的router, handler与context等相关API概念
  • 舍弃github.com/gin-gonic/gin的无关冗余部分, 例如binding...
  • 添加plugin的配置式设置

Documentation

Overview

如果换用gin框架, 下述API需要相应地转换

插件表达式语法: plugin(arg1,arg2,...), 参数之间使用逗号","分隔并忽略二侧空白. 其中(,)\是元字符,如果出现表在表达式内请使用转义字符"\"转义! 如果需要引用环境变量,请使用${NAME}的配置方法, 解析的参数类型都是string!

Index

Constants

View Source
const (
	AnnotationPath = "@Path"

	// protoServiceConfig的http_method用到的三种method, 其中WBSK是虚拟的.
	MethodWbsk = "WBSK"
	MethodGet  = http.MethodGet
	MethodPost = http.MethodPost
)
View Source
const (
	GRACE_FLAG = "__GRACE__" // 用于优雅重启传递环境变量
	GRACE_GRPC = "__GRPC__"
	GRACE_HTTP = "__HTTP__"
	GRACE_BOTH = "__BOTH__"
	GRACE_NONE = ""
)
View Source
const (
	InitGrpcGate int8 = 0
	InitPostGate int8 = 0
	InitWbskGate int8 = 0

	InitHttpMessageMaxLarge = 32 << 20 // 32 MB
)
View Source
const (
	HandlerChainMaxLength int8 = math.MaxInt8 / 2 // !关键: 每个path对应的HandlerChain的长度不能超过此值, 需要在Router的展开阶段进行严格控制
)
View Source
const (
	KEY = "protoweb"
)

Variables

View Source
var (
	GRPC = &Gate{grpcGate: 1}
	POST = &Gate{postGate: 1}
	WBSK = &Gate{wbskGate: 1}
	ON   = &Gate{grpcGate: 1, postGate: 1, wbskGate: 1}
)

Functions

func CallGrpcPlusFunc

func CallGrpcPlusFunc(expr string) (ret grpc.ServerOption, ok bool)

根据插件表达式获取相应的插件并返回处理结果

func CleanPath

func CleanPath(p string) string

CleanPath is the URL version of path.Clean, it returns a canonical URL path for p, eliminating . and .. elements.

The following rules are applied iteratively until no further processing can be done:

  1. Replace multiple slashes with a single slash.
  2. Eliminate each . path name element (the current directory).
  3. Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
  4. Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path.

If the result of this process is an empty string, "/" is returned

func EvaluateFunctionExpression

func EvaluateFunctionExpression(expr string) (name string, args []string)

plugin(arg1,arg2,...), 参数之间使用逗号","分隔并忽略二侧空白. 其中(,)\是元字符,如果出现表在表达式内请使用转义字符"\"转义! 1. 最左侧的(与最右侧的), 中间为args部分 2. 从左到右扫描",", 判断左边是否"\", 如果不是则作为分隔符, 如果是则作为普通字符! 如果出现参数以"\"结尾的情况, 请在","前加个空格!

func GetListenerFile

func GetListenerFile(l net.Listener) *os.File

func MethodEquals

func MethodEquals(m1, m2 string) bool

约定WBSK与GET是等同的

func PatternMatchs

func PatternMatchs(v string, ps ...string) bool

支持*与?的通配规则: 1. *表示任意字符 2. ?表示一个字符

func SetGrpcPlusFunc

func SetGrpcPlusFunc(n string, p GrpcPlusFunc)

func SetHttpPlusnc

func SetHttpPlusnc(n string, p HttpPlusFunc)

func WriteErrorResult

func WriteErrorResult(ctx *Context, err error, tag string) error

func WriteErrorResult2

func WriteErrorResult2(ctx *Context, code int, err error, tag string) error

func WriteFailureResult

func WriteFailureResult(ctx *Context, code int, msg string, tag string) error

func WriteResult

func WriteResult(ctx *Context, status int, r *base.Result) error

func WriteSuccessResult

func WriteSuccessResult(ctx *Context, data interface{}, tag string) error

Types

type Config

type Config struct {
	Name                string                 `json:"name" toml:"name"`                                     // service name
	GrpcAddr            string                 `json:"grpc_addr" toml:"grpc_addr"`                           // grpc server listening address
	GrpcKeepAlive       time.Duration          `json:"grpc_keep_alive" toml:"grpc_keep_alive"`               // grpc server keep alive
	GrpcPlus            []string               `json:"grpc_plus" toml:"grpc_plus"`                           // ServerOption plugins for grpc server
	HttpAddr            string                 `json:"http_addr" toml:"http_addr"`                           // http server listening address
	HttpKeepAlive       time.Duration          `json:"http_keep_alive" toml:"http_keep_alive"`               // http server keep alive
	HttpCertFile        string                 `json:"http_cert_file" toml:"http_cert_file"`                 // http server TLS cert file
	HttpKeyFile         string                 `json:"http_key_file" toml:"http_key_file"`                   // http server TLS key file
	HttpMessageMaxLarge int64                  `json:"http_message_max_large" toml:"http_message_max_large"` // Multipart reader's max memory bytes. It returns ErrMessageTooLarge if all non-file parts can't be stored in memory. default 10 MB
	WbskReadBufferSize  int                    `json:"wbsk_read_buffer_size" toml:"wbsk_read_buffer_size"`   // websocket read buffer size
	WbskWriteBufferSize int                    `json:"wbsk_write_buffer_Size" toml:"wbsk_write_buffer_Size"` // websocket write buffer size
	WbskNotCheckOrigin  bool                   `json:"wbsk_not_check_origin" toml:"wbsk_not_check_origin"`   // websocket would not check origin
	HttpPlus            []string               `json:"http_plus" toml:"http_plus"`                           // HandlerFunc plugins for http server
	HttpRule            []*HttpRuleConfig      `json:"http_rule" toml:"http_rule"`                           // AccessRule for http server
	ProtoGrpcGate       int8                   `json:"proto_grpc_gate" toml:"proto_grpc_gate"`               // add grpc access for all service, default off(-1)
	ProtoPostGate       int8                   `json:"proto_post_gate" toml:"proto_post_gate"`               // add post access for all service/method, default off(-1)
	ProtoWbskGate       int8                   `json:"proto_wbsk_gate" toml:"proto_wbsk_gate"`               // add wbsk access for all service/method, default off(-1)
	ProtoOpenRule       []*ProtoOpenRuleConfig `json:"proto_open_rule" toml:"proto_open_rule"`               // more detail config for every service
	ProtoPackagePrefix  string                 `json:"proto_package_prefix" toml:"proto_package_prefix"`     // prefix of package should be trim
	ProtoPackageSuffix  string                 `json:"proto_package_suffix" toml:"proto_package_suffix"`     // suffix of package should be trim
	ProtoServicePrefix  string                 `json:"proto_service_prefix" toml:"proto_service_prefix"`     // prefix of service should be trim
	ProtoServiceSuffix  string                 `json:"proto_service_suffix" toml:"proto_service_suffix"`     // suffix of service should be trim
	ProtoMethodPrefix   string                 `json:"proto_method_prefix" toml:"proto_method_prefix"`       // prefix of method should be trim
	ProtoMethodSuffix   string                 `json:"proto_method_suffix" toml:"proto_method_suffix"`       // suffix of method should be trim
}

func LoadConfig

func LoadConfig() (*Config, error)

func (*Config) BuildGrpcPlus

func (c *Config) BuildGrpcPlus() (ret []grpc.ServerOption)

func (*Config) BuildHttpPlus

func (c *Config) BuildHttpPlus() (ret []HandlerFunc)

func (*Config) Generate

func (c *Config) Generate(grpcPackage, grpcService, grpcMethod, annotations string) string

http path默认生成规则

type Context

type Context struct {

	// 需要重置的属性
	ResponseWriter http.ResponseWriter
	Request        *http.Request
	// contains filtered or unexported fields
}

func (*Context) Abort

func (c *Context) Abort()

func (*Context) AbortWithStatus

func (c *Context) AbortWithStatus(code int)

func (*Context) BindForm added in v0.0.102

func (c *Context) BindForm(obj interface{}) error

tag: form

func (*Context) BindJson added in v0.0.102

func (c *Context) BindJson(obj interface{}) error

func (*Context) BindQuery added in v0.0.102

func (c *Context) BindQuery(obj interface{}) error

tag: form

func (*Context) Deadline

func (c *Context) Deadline() (deadline time.Time, ok bool)

func (*Context) Done

func (c *Context) Done() <-chan struct{}

func (*Context) Err

func (c *Context) Err() error

func (*Context) Error added in v0.0.102

func (c *Context) Error(err error) error

func (*Context) FormValue added in v0.0.102

func (c *Context) FormValue(key string) string

func (*Context) Get

func (c *Context) Get(key string) (ret interface{}, ok bool)

func (*Context) Header added in v0.0.102

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

func (*Context) HeaderValue added in v0.0.102

func (c *Context) HeaderValue(key string) string

func (*Context) IsAborted

func (c *Context) IsAborted() bool

func (*Context) Next

func (c *Context) Next()

func (*Context) ParamValue added in v0.0.102

func (c *Context) ParamValue(key string) string

func (*Context) PostFormValue added in v0.0.102

func (c *Context) PostFormValue(key string) string

func (*Context) QueryValue added in v0.0.102

func (c *Context) QueryValue(key string) string

func (*Context) ReadBody added in v0.0.102

func (c *Context) ReadBody() ([]byte, error)

func (*Context) Set

func (c *Context) Set(key string, val interface{})

func (*Context) Value

func (c *Context) Value(key interface{}) interface{}

func (*Context) Write added in v0.0.102

func (c *Context) Write(status int, r io.Reader) (err error)

func (*Context) WriteHtml added in v0.0.102

func (c *Context) WriteHtml(status int, content string) (err error)

it should escape html before this method for security

func (*Context) WriteJson added in v0.0.102

func (c *Context) WriteJson(status int, obj interface{}) error

func (*Context) WritePlain added in v0.0.102

func (c *Context) WritePlain(status int, content string) (err error)

type Gate

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

func (*Gate) Apply

func (g *Gate) Apply(s *ProtoService)

type GrpcPlusFunc

type GrpcPlusFunc interface {
	Call(args []string) grpc.ServerOption // 插件调用
}

func GetGrpcPlusFunc

func GetGrpcPlusFunc(n string) (p GrpcPlusFunc, ok bool)

type HandlerChain added in v0.0.102

type HandlerChain []HandlerFunc

type HandlerFunc

type HandlerFunc func(ctx *Context)

func CallHttpPlusFunc

func CallHttpPlusFunc(expr string) (ret HandlerFunc, ok bool)

根据插件表达式获取相应的插件并返回处理结果

func PostHandlerFunc

func PostHandlerFunc(tag string, adapter func(ctx context.Context, in io.Reader) (interface{}, error)) HandlerFunc

func WbskHandlerFunc

func WbskHandlerFunc(tag string, adapter func(ctx context.Context, in io.Reader) (interface{}, error), upgrader *websocket.Upgrader, errorf func(format string, args ...interface{})) HandlerFunc

type HttpNode

type HttpNode struct {
	Package   string
	Service   string
	Method    string
	HttpGate  int8 // 是否关闭该规则
	Handlers  []HandlerFunc
	GroupPlus []HandlerFunc // 中间过程辅助属性:在router进行flattern时将group及父级以上的plus全部组装在此!
	RulesPlus []HandlerFunc // 中间过程辅助属性:来httprule处理时将httpRule的plus全部组装在此!
}

plus: conf.httpPlus+server.HttpPlus+conf.HttpRules+server.httpRules+groupPlus

type HttpPathGenerator

type HttpPathGenerator interface {
	Generate(grpcPackage, grpcService, grpcMethod, annotations string) string
}

type HttpPlusFunc

type HttpPlusFunc interface {
	Call(args []string) HandlerFunc // 插件调用
}

func GetHttpPlusFunc

func GetHttpPlusFunc(n string) (p HttpPlusFunc, ok bool)

type HttpRuleConfig

type HttpRuleConfig struct {
	Package    string   `json:"package" toml:"package"`         // package from proto
	Service    string   `json:"service" toml:"service"`         // service from proto
	Method     string   `json:"method" toml:"method"`           // method from proto
	HttpGate   int8     `json:"http_gate" toml:"http_gate"`     // 是否关闭该规则
	HttpMethod string   `json:"http_method" toml:"http_method"` // http method
	HttpPath   string   `json:"http_path" toml:"http_path"`     // http path
	HttpPlus   []string `json:"http_plus" toml:"http_plus"`     // http plus
}

在conf设定的http access过滤规则(也作用于grpc method的http/wbsk访问方式)

func (*HttpRuleConfig) Apply

func (c *HttpRuleConfig) Apply(node *HttpNode, httpMethod string, httpPath string, all map[string]map[string]*HttpNode)

type HttpRuleOption

type HttpRuleOption interface {
	Apply(node *HttpNode, httpMethod string, httpPath string, all map[string]map[string]*HttpNode)
}

type KeepAliveTCPListener

type KeepAliveTCPListener struct {
	*net.TCPListener
	KeepAlivePeriod time.Duration
}

tcpKeepAliveListener sets TCP keep-alive timeouts on accepted connections. It's used by ListenAndServe and ListenAndServeTLS so dead TCP connections (e.g. closing laptop mid-download) eventually go away.

func (KeepAliveTCPListener) Accept

func (ln KeepAliveTCPListener) Accept() (net.Conn, error)

type PanicFunc

type PanicFunc func(w http.ResponseWriter, r *http.Request, p interface{})

type Param

type Param struct {
	Key   string
	Value string
}

type Params

type Params []Param

func (Params) ByName

func (ps Params) ByName(name string) string

func (Params) Get

func (ps Params) Get(name string) (string, bool)

type ProtoMethod

type ProtoMethod struct {
	Adapter     func(context.Context, io.Reader) (interface{}, error)
	PostGate    int8 // 是否开启POST
	PostPath    string
	WbskGate    int8
	WbskPath    string
	Annotations string // the comments leading with "@xxx" prefix
}

因为plus(plugins)与其他属性的设置是相反的, plus需要从上往下按顺序, 而且conf的顺序需要在code顺序之前. 所以建议在Proto设置里面附加plus的处理 关于plus的处理统一放在HttpRule部分, 而且httpMethod=GET/WBSK都附加给WbskPlus, httpMethod=POST的则附加给PostPlus

type ProtoOpenRuleConfig

type ProtoOpenRuleConfig struct {
	Package  string `json:"package" toml:"package"`     // package
	Service  string `json:"service" toml:"service"`     // service
	Method   string `json:"method" toml:"method"`       // method
	GrpcGate int8   `json:"grpc_gate" toml:"grpc_gate"` // grpc switch
	PostGate int8   `json:"post_gate" toml:"post_gate"` // post switch
	PostPath string `json:"post_path" toml:"post_path"` // post path to instead
	WbskGate int8   `json:"wbsk_gate" toml:"wbsk_gate"` // wbsk switch
	WbskPath string `json:"wbsk_path" toml:"wbsk_path"` // wbsk path to instead
}

func (*ProtoOpenRuleConfig) Apply

func (c *ProtoOpenRuleConfig) Apply(s *ProtoService)

type ProtoOpenRuleOption

type ProtoOpenRuleOption interface {
	Apply(service *ProtoService)
}

type ProtoService

type ProtoService struct {
	Desc               *grpc.ServiceDesc       // grpc的service描述符
	Impl               interface{}             // grpc的service实现实例
	Package            string                  // grpc的package名称
	Service            string                  // grpc的service名称
	Methods            map[string]*ProtoMethod // 方法的http适配器
	GrpcGate           int8                    // 是否开始grpc
	ProtoServiceConfig []ProtoOpenRuleOption   // proto service option
}

type Router

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

func (*Router) Any

func (rc *Router) Any(path string, f ...HandlerFunc) *Router

func (*Router) Connect

func (rc *Router) Connect(path string, f ...HandlerFunc) *Router

func (*Router) DELETE

func (rc *Router) DELETE(path string, f ...HandlerFunc) *Router

func (*Router) GET

func (rc *Router) GET(path string, f ...HandlerFunc) *Router

func (*Router) Group

func (rc *Router) Group(path string, hs ...HandlerFunc) *Router

func (*Router) HEAD

func (rc *Router) HEAD(path string, f ...HandlerFunc) *Router

func (*Router) Handle

func (rc *Router) Handle(method string, path string, hs ...HandlerFunc) *Router

func (*Router) OPTIONS

func (rc *Router) OPTIONS(path string, f ...HandlerFunc) *Router

func (*Router) PATCH

func (rc *Router) PATCH(path string, f ...HandlerFunc) *Router

func (*Router) POST

func (rc *Router) POST(path string, f ...HandlerFunc) *Router

func (*Router) PUT

func (rc *Router) PUT(path string, f ...HandlerFunc) *Router

func (*Router) Static

func (rc *Router) Static(path string, dir string) *Router

func (*Router) StaticFS

func (rc *Router) StaticFS(path string, fs http.FileSystem) *Router

func (*Router) StaticFile

func (rc *Router) StaticFile(path string, file string) *Router

func (*Router) Trace

func (rc *Router) Trace(path string, f ...HandlerFunc) *Router

func (*Router) Use

func (rc *Router) Use(plus ...HandlerFunc) *Router

type Server

type Server struct {

	// 路由冗余配置及中间结果,在Serve()方法最后会自动清理掉
	*Router // 路由配置信息,
	// contains filtered or unexported fields
}

实现: kill -TERM/-QUIT graceful shutdown kill -HUB graceful restart kill -USR1/-USR2 reload config only

func NewServer

func NewServer() *Server

func (*Server) ErrorLogger added in v0.0.104

func (s *Server) ErrorLogger(f func(string, ...interface{})) *Server

设置错误日志输出

func (*Server) GrpcCall

func (s *Server) GrpcCall(f func(s *grpc.Server)) *Server

func (*Server) GrpcPlus

func (s *Server) GrpcPlus(fs ...grpc.ServerOption) *Server

func (*Server) HttpPlus

func (s *Server) HttpPlus(fs ...HandlerFunc) *Server

添加路由过滤规则, 跟RouterConfig.Use()效果是等同的

func (*Server) HttpRule

func (s *Server) HttpRule(vs ...HttpRuleOption) *Server

func (*Server) NotFound

func (m *Server) NotFound(fs ...HandlerFunc)

func (*Server) Panic

func (m *Server) Panic(f PanicFunc)

func (*Server) ProtoGrpcGate

func (s *Server) ProtoGrpcGate(v int8) *Server

func (*Server) ProtoPostGate

func (s *Server) ProtoPostGate(v int8) *Server

func (*Server) ProtoServiceConfig

func (s *Server) ProtoServiceConfig(vs ...ProtoOpenRuleOption) *Server

func (*Server) ProtoWbskGate

func (s *Server) ProtoWbskGate(v int8) *Server

func (*Server) RegisterService

func (s *Server) RegisterService(rf func(impl interface{}) (*grpc.ServiceDesc, string, string, map[string]func(context.Context, io.Reader) (interface{}, error), map[string]string), impl interface{}, opts ...ProtoOpenRuleOption) *Server

func (*Server) Serve

func (s *Server) Serve() error

func (*Server) ServeHTTP

func (m *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Server) ServeWith

func (s *Server) ServeWith(c *Config) (err error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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