cosweb

package
v0.0.0-...-f82ef47 Latest Latest
Warning

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

Go to latest
Published: May 16, 2021 License: Apache-2.0 Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const (
	RouteGroupPath = "_RouteGroupPath"
	RouteGroupName = "_RouteGroupName"
)
View Source
const (
	HeaderAccept              = "Accept"
	HeaderAcceptEncoding      = "Accept-Encoding"
	HeaderAllow               = "Allow"
	HeaderAuthorization       = "Authorization"
	HeaderContentDisposition  = "Content-Disposition"
	HeaderContentEncoding     = "Content-Encoding"
	HeaderContentLength       = "Content-Length"
	HeaderContentType         = "Content-Type"
	HeaderCookie              = "Cookie"
	HeaderSetCookie           = "Set-Cookie"
	HeaderIfModifiedSince     = "If-Modified-Since"
	HeaderLastModified        = "Last-Modified"
	HeaderLocation            = "Location"
	HeaderUpgrade             = "Upgrade"
	HeaderVary                = "Vary"
	HeaderWWWAuthenticate     = "WWW-Authenticate"
	HeaderXForwardedFor       = "X-Forwarded-For"
	HeaderXForwardedProto     = "X-Forwarded-Proto"
	HeaderXForwardedProtocol  = "X-Forwarded-Protocol"
	HeaderXForwardedSsl       = "X-Forwarded-Ssl"
	HeaderXUrlScheme          = "X-Url-Protocol"
	HeaderXHTTPMethodOverride = "X-HTTP-value-Override"
	HeaderXRealIP             = "X-Real-Addr"
	HeaderXRequestID          = "X-Request-ID"
	HeaderXRequestedWith      = "X-Requested-With"
	HeaderServer              = "Server"
	HeaderOrigin              = "origin"

	// Access control
	HeaderAccessControlRequestMethod    = "Access-Control-Request-value"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-origin"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"

	// Security
	HeaderStrictTransportSecurity         = "Strict-Transport-Security"
	HeaderXContentTypeOptions             = "X-Content-Type-options"
	HeaderXXSSProtection                  = "X-XSS-Protection"
	HeaderXFrameOptions                   = "X-Frame-options"
	HeaderContentSecurityPolicy           = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	HeaderXCSRFToken                      = "X-CSRF-Token"
	HeaderReferrerPolicy                  = "Referrer-Policy"
)

Headers

View Source
const (
	MIMETextHTML  = "text/html"
	MIMETextPlain = "text/plain"

	MIMETextXML         = "text/xml"
	MIMEApplicationJS   = "application/javascript"
	MIMEApplicationXML  = "application/xml"
	MIMEApplicationJSON = "application/json"

	MIMEApplicationProtobuf = "application/protobuf"
	MIMEApplicationMsgpack  = "application/msgpack"

	MIMEOctetStream = "application/octet-stream"

	MIMEMultipartForm   = "multipart/form-store"
	MIMEApplicationForm = "application/x-www-form-urlencoded"
)

MIME types

View Source
const (
	MIMETextHTMLCharsetUTF8  = MIMETextHTML + "; " + charsetUTF8
	MIMETextPlainCharsetUTF8 = MIMETextPlain + "; " + charsetUTF8

	MIMETextXMLCharsetUTF8 = MIMETextXML + "; " + charsetUTF8

	MIMEApplicationJSCharsetUTF8   = MIMEApplicationJS + "; " + charsetUTF8
	MIMEApplicationXMLCharsetUTF8  = MIMEApplicationXML + "; " + charsetUTF8
	MIMEApplicationJSONCharsetUTF8 = MIMEApplicationJSON + "; " + charsetUTF8
)

MIME UTF8 types

View Source
const (
	RequestDataTypeParam  int = iota //params
	RequestDataTypeBody              //POST FORM
	RequestDataTypeQuery             //GET
	RequestDataTypeCookie            //COOKIES
	RequestDataTypeHeader            //HEADER
)
View Source
const (
	RoutePathName_Param string = ":"
	RoutePathName_Vague string = "*"
)

Variables

View Source
var (
	ErrUnsupportedMediaType        = NewHTTPError(http.StatusUnsupportedMediaType)
	ErrNotFound                    = NewHTTPError(http.StatusNotFound)
	ErrUnauthorized                = NewHTTPError(http.StatusUnauthorized)
	ErrForbidden                   = NewHTTPError(http.StatusForbidden)
	ErrMethodNotAllowed            = NewHTTPError(http.StatusMethodNotAllowed)
	ErrStatusRequestEntityTooLarge = NewHTTPError(http.StatusRequestEntityTooLarge)
	ErrTooManyRequests             = NewHTTPError(http.StatusTooManyRequests)
	ErrBadRequest                  = NewHTTPError(http.StatusBadRequest)
	ErrBadGateway                  = NewHTTPError(http.StatusBadGateway)
	ErrInternalServerError         = NewHTTPError(http.StatusInternalServerError)
	ErrRequestTimeout              = NewHTTPError(http.StatusRequestTimeout)
	ErrServiceUnavailable          = NewHTTPError(http.StatusServiceUnavailable)
	ErrValidatorNotRegistered      = errors.New("validator not registered")
	ErrRendererNotRegistered       = errors.New("renderer not registered")
	ErrInvalidRedirectCode         = errors.New("invalid redirect status code")
	ErrCookieNotFound              = errors.New("cookie not found")
	ErrInvalidCertOrKeyType        = errors.New("invalid cert or key type, must be string or []byte")
)

Errors

View Source
var (
	AnyHttpMethod = []string{
		http.MethodGet,
		http.MethodHead,
		http.MethodPost,
		http.MethodPut,
		http.MethodPatch,
		http.MethodDelete,
		http.MethodConnect,
		http.MethodOptions,
		http.MethodTrace,
	}
	// Error handlers
	MethodNotFoundHandler = func(c *Context) error {
		return ErrNotFound
	}
)

Functions

func GetDataFromRequest

func GetDataFromRequest(c *Context, key string, dataType int) (string, bool)

func TLSConfigAutocert

func TLSConfigAutocert() (c *tls.Config, err error)

createTLS starts an HTTPS server using certificates automatically installed from https://letsencrypt.org.

func TLSConfigParse

func TLSConfigParse(certFile, keyFile interface{}) (TLSConfig *tls.Config, err error)

通过文件或者证书内容获取TLSConfig

func TLSConfigTransform

func TLSConfigTransform(key, pem string) (c *tls.Config, err error)

Types

type Binder

type Binder interface {
	Bind(c *Context, i interface{}) error
}

Binder is the interface that wraps the Bind value.

type Context

type Context struct {
	Path     string
	Server   *Server
	Session  *Session
	Request  *http.Request
	Response http.ResponseWriter
	// contains filtered or unexported fields
}

Context API上下文.

func NewContext

func NewContext(s *Server, r *http.Request, w http.ResponseWriter) *Context

NewContext returns a Context instance.

func (*Context) Aborted

func (c *Context) Aborted() bool

Aborted 是否已经被中断

func (*Context) Attachment

func (c *Context) Attachment(file, name string) error

func (*Context) Bind

func (c *Context) Bind(i interface{}) error

Bind 绑定JSON XML

func (*Context) Bytes

func (c *Context) Bytes(contentType string, b []byte) (err error)

func (*Context) End

func (c *Context) End() error

结束响应,返回空内容

func (*Context) Error

func (c *Context) Error(err error)

func (*Context) File

func (c *Context) File(file string) (err error)

func (*Context) Flush

func (c *Context) Flush()

Flush implements the http.Flusher interface to allow an HTTP Handler to flush buffered store to the client. See http.Flusher(https://golang.org/pkg/net/http/#Flusher)

func (*Context) Get

func (c *Context) Get(key string, dts ...int) string

Get 获取参数,优先路径中的params 其他方式直接使用c.Request...

func (*Context) HTML

func (c *Context) HTML(html string) (err error)

func (*Context) Header

func (c *Context) Header() http.Header

func (*Context) Hijack

func (c *Context) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack implements the http.Hijacker interface to allow an HTTP Handler to take over the connection. See http.Hijacker(https://golang.org/pkg/net/http/#Hijacker)

func (*Context) Inline

func (c *Context) Inline(file, name string) error

func (*Context) IsWebSocket

func (c *Context) IsWebSocket() bool

IsWebSocket 判断是否WebSocket

func (*Context) JSON

func (c *Context) JSON(i interface{}) error

func (*Context) JSONP

func (c *Context) JSONP(callback string, i interface{}) error

func (*Context) Protocol

func (c *Context) Protocol() string

Protocol 协议

func (*Context) Redirect

func (c *Context) Redirect(url string) error

func (*Context) RemoteAddr

func (c *Context) RemoteAddr() string

RemoteAddr 客户端地址

func (*Context) Render

func (c *Context) Render(name string, data interface{}) (err error)

func (*Context) SetCookie

func (c *Context) SetCookie(cookie *http.Cookie)

func (*Context) Stream

func (c *Context) Stream(contentType string, r io.Reader) (err error)

func (*Context) String

func (c *Context) String(s string) (err error)

func (*Context) Write

func (c *Context) Write(b []byte) (n int, err error)

Write writes the store to the connection as part of an HTTP reply.

func (*Context) WriteHeader

func (c *Context) WriteHeader(code int)

Status sends an HTTP Response header with status code. If Status is not called explicitly, the first call to Write will trigger an implicit Status(http.StatusOK). Thus explicit calls to Status are mainly used to send error codes.

func (*Context) XML

func (c *Context) XML(i interface{}, indent string) (err error)

type DefaultBinder

type DefaultBinder struct{}

DefaultBinder is the default implementation of the Binder interface.

func (*DefaultBinder) Bind

func (b *DefaultBinder) Bind(c *Context, i interface{}) (err error)

Bind implements the `Binder#Bind` function.

type Group

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

Group 使用反射集中注册方法 可以使用 /prefix/$Group/$value 的格式访问

func NewGroup

func NewGroup(mode GroupMode) *Group

NewGroup 创建新的路由组

func (*Group) Register

func (g *Group) Register(handle interface{}) error

Register 注册一组handle,重名忽略

func (*Group) Route

func (g *Group) Route(s *Server, prefix string, method ...string)

Route 将Group添加到服务器Route

func (*Group) SetCaller

func (g *Group) SetCaller(f GroupCaller)

SetCaller 设置Group的caller

func (*Group) Use

func (g *Group) Use(m ...MiddlewareFunc)

Use 使用中间件,只针对GROUP下的API

type GroupCaller

type GroupCaller func(reflect.Value, reflect.Value, *Context) error

GroupCaller 建议为每个注册的struct对象封装一个caller方法可以避免使用 reflect.Value.Call()方法

type GroupMode

type GroupMode int
const (
	GroupModeEasy   GroupMode = 0 //不区分大小写
	GroupModeStrict GroupMode = 1 //区分大小写
)

type GroupNode

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

GroupNode 节点,每个节点对应一个容器以及容器下面的所有接口

func NewGroupNode

func NewGroupNode(handle interface{}) *GroupNode

NewGroupNode NewGroupNode

type HTTPError

type HTTPError struct {
	Code    int         `json:"-"`
	Message interface{} `json:"message"`
}

HTTPError represents an error that occurred while handling a Request.

func NewHTTPError

func NewHTTPError(code int, message ...interface{}) *HTTPError

NewHTTPError creates a new HTTPError instance.

func NewHTTPError500

func NewHTTPError500(message interface{}) *HTTPError

func (*HTTPError) Error

func (he *HTTPError) Error() string

Error makes it compatible with `error` interface.

func (*HTTPError) String

func (he *HTTPError) String(debug bool) string

type HTTPErrorHandler

type HTTPErrorHandler func(*Context, error)

HTTPErrorHandler is a centralized HTTP error Handler.

type HandlerFunc

type HandlerFunc func(*Context) error

HandlerFunc defines a function to serve HTTP requests.

type MiddlewareFunc

type MiddlewareFunc func(*Context, func())

MiddlewareFunc defines a function to process middleware.

type Node

type Node struct {
	Route   []string    //当前路由绝对路径
	Handler HandlerFunc //handler入口
	// contains filtered or unexported fields
}

func NewNode

func NewNode(step int, name string) *Node

func (*Node) Params

func (this *Node) Params(path string) map[string]string

func (*Node) String

func (this *Node) String() string

type Options

type Options struct {
	SessionKey     string
	SessionType    []int //存放SESSION KEY的方式
	SessionSecret  string
	SessionStorage session.Storage //Session数据存储器
}

func NewOptions

func NewOptions() *Options

type Proxy

type Proxy struct {
	GetTarget func(*Context, []*url.URL) url.URL //获取目标服务器地址,适用于负载均衡
	// contains filtered or unexported fields
}

func NewProxy

func NewProxy(address ...string) *Proxy

func (*Proxy) AddTarget

func (this *Proxy) AddTarget(addr string) error

添加代理服务器地址

func (*Proxy) Route

func (this *Proxy) Route(s *Server, prefix string, method ...string)

type RESTful

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

func NewRESTful

func NewRESTful() *RESTful

func (*RESTful) Register

func (this *RESTful) Register(handle iRESTful)

Register 注册一组handle,重名忽略

func (*RESTful) Route

func (this *RESTful) Route(s *Server, prefix string, method ...string)

type Renderer

type Renderer interface {
	Render(io.Writer, string, interface{}, *Context) error
}

Renderer is the interface that wraps the Render function.

type Router

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

Router is the registry of all registered Routes for an `Server` instance for Request matching and URL path parameter parsing.

func NewRouter

func NewRouter() *Router

func (*Router) Match

func (r *Router) Match(method, path string) *Node
  /s/:id/update
	/s/123

func (*Router) Register

func (r *Router) Register(route string, handler HandlerFunc, method ...string)

type Server

type Server struct {
	Router *Router

	Debug            bool //DEBUG模式会打印所有路由匹配状态,向客户端输出详细错误信息
	Binder           Binder
	Server           *http.Server
	Options          *Options
	Renderer         Renderer
	HTTPErrorHandler HTTPErrorHandler
	// contains filtered or unexported fields
}

Server is the top-level framework instance.

func NewServer

func NewServer(address string, tlsConfig ...*tls.Config) (e *Server)

New creates an instance of Server.

func (*Server) AcquireContext

func (s *Server) AcquireContext(w http.ResponseWriter, r *http.Request) *Context

AcquireContext returns an empty `Ctx` instance from the pool. You must return the Context by calling `ReleaseContext()`.

func (*Server) Any

func (s *Server) Any(path string, h HandlerFunc)

Any registers a new Register for all HTTP methods and path with matching Handler in the Router with optional Register-level middleware.

func (*Server) Close

func (s *Server) Close() error

立即关闭

func (*Server) DefaultHTTPErrorHandler

func (s *Server) DefaultHTTPErrorHandler(c *Context, err error)

DefaultHTTPErrorHandler is the default HTTP error Handler. It sends a JSON Response with status code.

func (*Server) GET

func (s *Server) GET(path string, h HandlerFunc)

GET registers a new GET Register for a path with matching Handler in the Router with optional Register-level middleware.

func (*Server) Group

func (s *Server) Group(prefix string, i interface{}, method ...string) *Group

Group 注册路由组

func (*Server) POST

func (s *Server) POST(path string, h HandlerFunc)

POST registers a new POST Register for a path with matching Handler in the Router with optional Register-level middleware.

func (*Server) Proxy

func (s *Server) Proxy(prefix, address string, method ...string) *Proxy

代理服务器

func (*Server) RESTful

func (s *Server) RESTful(prefix string, handle iRESTful, method ...string) *RESTful

func (*Server) Register

func (s *Server) Register(path string, handler HandlerFunc, method ...string)

AddTarget registers a new Register for an HTTP value and path with matching Handler in the Router with optional Register-level middleware.

func (*Server) ReleaseContext

func (s *Server) ReleaseContext(c *Context)

ReleaseContext returns the `Ctx` instance back to the pool. You must call it after `AcquireContext()`.

func (*Server) ServeHTTP

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

ServeHTTP implements `http.Handler` interface, which serves HTTP requests.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx ctx.Context) error

优雅关闭,等所有协程结束

func (*Server) Start

func (s *Server) Start() (err error)

Start starts an HTTP server.

func (*Server) Static

func (s *Server) Static(prefix, root string, method ...string) *Static

Static registers a new Register with path prefix to serve static files from the provided root directory. 如果root 不是绝对路径 将以程序的WorkDir为基础

func (*Server) Use

func (s *Server) Use(middleware ...MiddlewareFunc)

Use adds middleware to the chain which is run after Router.

type Session

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

func NewSession

func NewSession(s *Server, c *Context) *Session

func (*Session) Get

func (this *Session) Get(key string) (interface{}, bool)

func (*Session) New

func (this *Session) New(key string, val map[string]interface{}) (string, error)

func (*Session) Set

func (this *Session) Set(key string, val interface{}) bool

func (*Session) Start

func (this *Session) Start(level int) error

type Static

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

func NewStatic

func NewStatic(root string) *Static

func (*Static) Route

func (this *Static) Route(s *Server, prefix string, method ...string)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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