Documentation ¶
Index ¶
- Constants
- Variables
- func DELETE(path string, handler HandlerFunc, opts ...ServerOption)
- func DetectError(err error) (int, string, error)
- func DetectErrorCode(err error) string
- func DetectStatusCode(err error) int
- func GET(path string, handler HandlerFunc, opts ...ServerOption)
- func HEAD(path string, handler HandlerFunc, opts ...ServerOption)
- func Handle(method, path string, handler HandlerFunc, opts ...ServerOption)
- func MiddlewareHandler(phs ...ProgressHandler) http.Handler
- func MiddlewareHandlerFunc(phs ...ProgressHandler) http.HandlerFunc
- func MiddlewareHandlerFuncWith(r *Router, phs ...ProgressHandler) http.HandlerFunc
- func MiddlewareHandlerWith(r *Router, phs ...ProgressHandler) http.Handler
- func NewTransport(cfg *TransportConfig) http.RoundTripper
- func OPTIONS(path string, handler HandlerFunc, opts ...ServerOption)
- func PATCH(path string, handler HandlerFunc, opts ...ServerOption)
- func POST(path string, handler HandlerFunc, opts ...ServerOption)
- func PUT(path string, handler HandlerFunc, opts ...ServerOption)
- func ParseData(resp *http.Response, data interface{}) (err error)
- func ParseResponseErr(resp *http.Response) (err error)
- func RegisterArgsParser(args interface{}, tags ...string)
- func ReplyErr(w http.ResponseWriter, code int, err string)
- func ReplyWith(w http.ResponseWriter, code int, bodyType string, msg []byte)
- func Use(interceptors ...HandlerFunc)
- type Client
- type Config
- type Context
- func (c *Context) Abort()
- func (c *Context) AbortWithError(err error)
- func (c *Context) AbortWithStatus(statusCode int)
- func (c *Context) AbortWithStatusJSON(statusCode int, obj interface{})
- func (c *Context) ArgsBody(args interface{}) error
- func (c *Context) ArgsForm(args interface{}) error
- func (c *Context) ArgsPostForm(args interface{}) error
- func (c *Context) ArgsQuery(args interface{}) error
- func (c *Context) ArgsURI(args interface{}) error
- func (c *Context) Flush()
- func (c *Context) Get(key string) (val interface{}, exists bool)
- func (c *Context) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (c *Context) IsAborted() bool
- func (c *Context) Next()
- func (c *Context) ParseArgs(args interface{}, opts ...ServerOption) error
- func (c *Context) Pusher() http.Pusher
- func (c *Context) RemoteIP() (net.IP, bool)
- func (c *Context) RequestLength() (int, error)
- func (c *Context) Respond()
- func (c *Context) RespondError(err error)
- func (c *Context) RespondJSON(obj interface{})
- func (c *Context) RespondStatus(statusCode int)
- func (c *Context) RespondStatusData(statusCode int, obj interface{})
- func (c *Context) RespondWith(statusCode int, contentType string, body []byte)
- func (c *Context) RespondWithReader(statusCode int, contentLength int, contentType string, body io.Reader, ...)
- func (c *Context) Set(key string, val interface{})
- func (c *Context) Stream(step func(w io.Writer) bool) bool
- type Error
- type HTTPError
- type HandlerFunc
- type LbConfig
- type Marshaler
- type MarshalerTo
- type Option
- type Parser
- type ProgressHandler
- type Router
- type Selector
- type ServerOption
- type TransportConfig
- type Unmarshaler
- type UnmarshalerFrom
- type ValueGetter
Constants ¶
const ( HeaderContentType = "Content-Type" HeaderContentLength = "Content-Length" HeaderContentRange = "Content-Range" HeaderContentMD5 = "Content-MD5" HeaderUA = "User-Agent" // trace HeaderTraceLog = "Trace-Log" HeaderTraceTags = "Trace-Tags" // crc checker HeaderCrcEncoded = "X-Crc-Encoded" HeaderAckCrcEncoded = "X-Ack-Crc-Encoded" )
headers
const ( MIMEStream = "application/octet-stream" MIMEJSON = "application/json" MIMEXML = "application/xml" MIMEPlain = "text/plain" MIMEPOSTForm = "application/x-www-form-urlencoded" MIMEMultipartPOSTForm = "multipart/form-data" MIMEYAML = "application/x-yaml" )
mime
const (
GzipEncodingType = "gzip"
)
encoding
Variables ¶
var ErrBodyReadTimeout = errors.New("read body timeout")
ErrBodyReadTimeout timeout error
var UserAgent = "Golang blobstore/rpc package"
UserAgent user agent
Functions ¶
func DELETE ¶
func DELETE(path string, handler HandlerFunc, opts ...ServerOption)
DELETE is a shortcut for Handle(http.MethodDelete, path, handle)
func DetectError ¶
DetectError returns status code, error code, error
func DetectStatusCode ¶
DetectStatusCode returns http status code
func GET ¶
func GET(path string, handler HandlerFunc, opts ...ServerOption)
GET is a shortcut for Handle(http.MethodGet, path, handle)
func HEAD ¶
func HEAD(path string, handler HandlerFunc, opts ...ServerOption)
HEAD is a shortcut for Handle(http.MethodHead, path, handle)
func Handle ¶
func Handle(method, path string, handler HandlerFunc, opts ...ServerOption)
Handle registers a new request handle with the given path and method.
For HEAD, GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used.
func MiddlewareHandler ¶
func MiddlewareHandler(phs ...ProgressHandler) http.Handler
MiddlewareHandler middleware above rpc server default router. Run sorted by progress handler order.
func MiddlewareHandlerFunc ¶
func MiddlewareHandlerFunc(phs ...ProgressHandler) http.HandlerFunc
MiddlewareHandlerFunc middleware func above rpc server default router. Run sorted by progress handler order.
func MiddlewareHandlerFuncWith ¶
func MiddlewareHandlerFuncWith(r *Router, phs ...ProgressHandler) http.HandlerFunc
MiddlewareHandlerFuncWith middleware func above rpc server router Run sorted by progress handler order.
func MiddlewareHandlerWith ¶
func MiddlewareHandlerWith(r *Router, phs ...ProgressHandler) http.Handler
MiddlewareHandlerWith middleware above rpc server router Run sorted by progress handler order.
func NewTransport ¶
func NewTransport(cfg *TransportConfig) http.RoundTripper
NewTransport returns http transport
func OPTIONS ¶
func OPTIONS(path string, handler HandlerFunc, opts ...ServerOption)
OPTIONS is a shortcut for Handle(http.MethodOptions, path, handle)
func PATCH ¶
func PATCH(path string, handler HandlerFunc, opts ...ServerOption)
PATCH is a shortcut for Handle(http.MethodPatch, path, handle)
func POST ¶
func POST(path string, handler HandlerFunc, opts ...ServerOption)
POST is a shortcut for Handle(http.MethodPost, path, handle)
func PUT ¶
func PUT(path string, handler HandlerFunc, opts ...ServerOption)
PUT is a shortcut for Handle(http.MethodPut, path, handle)
func ParseResponseErr ¶
ParseResponseErr parse error of response
func RegisterArgsParser ¶
func RegisterArgsParser(args interface{}, tags ...string)
RegisterArgsParser regist your argument need parse in uri, query, form, or postform. the tags is sorted. NOTE: the function is thread-unsafe.
func ReplyErr ¶
func ReplyErr(w http.ResponseWriter, code int, err string)
ReplyErr directly reply error with response writer
func ReplyWith ¶
func ReplyWith(w http.ResponseWriter, code int, bodyType string, msg []byte)
ReplyWith directly reply body with response writer
func Use ¶
func Use(interceptors ...HandlerFunc)
Use attaches a global interceptor to the default router. You should Use interceptor before register handler. It is sorted by registered order.
Types ¶
type Client ¶
type Client interface { // Method*** handle response by yourself Do(ctx context.Context, req *http.Request) (*http.Response, error) Head(ctx context.Context, url string) (*http.Response, error) Get(ctx context.Context, url string) (*http.Response, error) Delete(ctx context.Context, url string) (*http.Response, error) Form(ctx context.Context, method, url string, form map[string][]string) (*http.Response, error) Put(ctx context.Context, url string, params interface{}) (*http.Response, error) Post(ctx context.Context, url string, params interface{}) (*http.Response, error) // ***With means parse result in client DoWith(ctx context.Context, req *http.Request, ret interface{}, opts ...Option) error GetWith(ctx context.Context, url string, ret interface{}) error PutWith(ctx context.Context, url string, ret interface{}, params interface{}, opts ...Option) error PostWith(ctx context.Context, url string, ret interface{}, params interface{}, opts ...Option) error // Close background goroutines in lb client Close() }
Client implements the rpc client with http
func NewLbClient ¶
NewLbClient returns a lb client
type Config ¶
type Config struct { // the whole request and response timeout ClientTimeoutMs int64 `json:"client_timeout_ms"` // bandwidthBPMs for read body BodyBandwidthMBPs float64 `json:"body_bandwidth_mbps"` // base timeout for read body BodyBaseTimeoutMs int64 `json:"body_base_timeout_ms"` // transport config Tc TransportConfig `json:"transport_config"` }
Config simple client config
type Context ¶
type Context struct { Param httprouter.Params Request *http.Request Writer http.ResponseWriter Meta map[string]interface{} // contains filtered or unexported fields }
Context handler context with http variables
func (*Context) AbortWithError ¶
AbortWithError abort with error
func (*Context) AbortWithStatus ¶
AbortWithStatus abort with status
func (*Context) AbortWithStatusJSON ¶
AbortWithStatusJSON abort with status and response data
func (*Context) ArgsPostForm ¶
ArgsPostForm args in post form
func (*Context) Get ¶
Get returns the value for the given key, If the value does not exists it returns (nil, false).
func (*Context) Next ¶
func (c *Context) Next()
Next should be used only inside interceptor. It executes the pending handlers inside the calling handler.
func (*Context) ParseArgs ¶
func (c *Context) ParseArgs(args interface{}, opts ...ServerOption) error
ParseArgs reflect param to args
func (*Context) RemoteIP ¶
RemoteIP parses the IP from Request.RemoteAddr, returns the net.IP (without the port).
func (*Context) RequestLength ¶
RequestLength read request body length
func (*Context) RespondError ¶
RespondError response error
func (*Context) RespondJSON ¶
func (c *Context) RespondJSON(obj interface{})
RespondJSON response json
func (*Context) RespondStatus ¶
RespondStatus response status code
func (*Context) RespondStatusData ¶
RespondStatusData response data with code
func (*Context) RespondWith ¶
RespondWith response with code, content-type, bytes
func (*Context) RespondWithReader ¶
func (c *Context) RespondWithReader(statusCode int, contentLength int, contentType string, body io.Reader, extraHeaders map[string]string)
RespondWithReader response with code, content-length, content-type, an io.Reader and extra headers
type HTTPError ¶
type HTTPError interface { // StatusCode http status code StatusCode() int // ErrorCode special defined code ErrorCode() string // Error detail message Error() string }
HTTPError interface of error with http status code
func Error2HTTPError ¶
Error2HTTPError returns an interface HTTPError from an error
type LbConfig ¶
type LbConfig struct { // hosts Hosts []string `json:"hosts"` // backup hosts BackupHosts []string `json:"backup_hosts"` // HostTryTimes Number of host failure retries, HostTryTimes < RequestTryTimes, // Avoid requesting the unavailable host all the time HostTryTimes int `json:"host_try_times"` // Failure retry interval, default value is -1, if FailRetryIntervalS < 0, // remove failed hosts will not work. FailRetryIntervalS int `json:"fail_retry_interval_s"` // Within MaxFailsPeriodS, if the number of failures is greater than or equal // to MaxFails, the host is considered disconnected. MaxFailsPeriodS int `json:"max_fails_period_s"` // RequestTryTimes The maximum number of attempts for a request hosts. RequestTryTimes int `json:"try_times"` // should retry function ShouldRetry func(code int, err error) bool `json:"-"` // config for simple client Config }
LbConfig load balance config
type Marshaler ¶
Marshaler is the interface implemented by types that can marshal themselves into bytes, second parameter is content type.
var NoneBody Marshaler = noneBody{}
NoneBody no body of request of response.
type MarshalerTo ¶
MarshalerTo is the interface implemented by types that can marshal themselves into writer, the first parameter is content type. (Not Recommended). The underlying writer is a *bytes.Buffer. Context.RespondWithReader is better than MarshalerTo on Server Side.
type Parser ¶
type Parser interface {
Parse(ValueGetter) error
}
Parser is the interface implemented by argument types that can parse themselves from url.Values.
type ProgressHandler ¶
type ProgressHandler interface {
Handler(http.ResponseWriter, *http.Request, func(http.ResponseWriter, *http.Request))
}
ProgressHandler http progress handler
type Router ¶
type Router struct { Router *httprouter.Router // router // contains filtered or unexported fields }
Router router with interceptors Interceptor is middleware for http serve but named `interceptor`. Middleware within this Router called `interceptor`.
headMiddlewares is middlewares run firstly. Running order is:
headMiddlewares --> middlewares --> interceptors --> handler
example: router := New() router.Use(interceptor1, interceptor2) router.Handle(http.MethodGet, "/get/:name", handlerGet) router.Handle(http.MethodPut, "/put/:name", handlerPut)
var DefaultRouter *Router
DefaultRouter default router for server
func (*Router) Handle ¶
func (r *Router) Handle(method, path string, handler HandlerFunc, opts ...ServerOption)
Handle registers a new request handle with the given path and method.
For HEAD, GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used.
func (*Router) ServeHTTP ¶
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
ServeHTTP makes the router implement the http.Handler interface.
func (*Router) Use ¶
func (r *Router) Use(interceptors ...HandlerFunc)
Use attaches a global interceptor to the router. You should Use interceptor before register handler. It is sorted by registered order.
type ServerOption ¶
type ServerOption interface {
// contains filtered or unexported methods
}
ServerOption server option applier Order: if args in body ignore others options,
else uri > query > form > postfrom
func OptMetaCapacity ¶
func OptMetaCapacity(capacity int) ServerOption
OptMetaCapacity initial meta capacity
type TransportConfig ¶
type TransportConfig struct { // DialTimeoutMs dial timeout in milliseconds DialTimeoutMs int64 `json:"dial_timeout_ms"` // ResponseHeaderTimeoutMs response header timeout after send the request ResponseHeaderTimeoutMs int64 `json:"response_header_timeout_ms"` MaxConnsPerHost int `json:"max_conns_per_host"` MaxIdleConns int `json:"max_idle_conns"` MaxIdleConnsPerHost int `json:"max_idle_conns_per_host"` // IdleConnTimeout is the maximum amount of time an idle // (keep-alive) connection will remain idle before closing // itself.Zero means no limit. IdleConnTimeoutMs int64 `json:"idle_conn_timeout_ms"` // DisableCompression, if true, prevents the Transport from // requesting compression with an "Accept-Encoding: gzip" DisableCompression bool `json:"disable_compression"` // auth config Auth auth.Config `json:"auth"` }
TransportConfig http transport config
func (TransportConfig) Default ¶
func (tc TransportConfig) Default() TransportConfig
Default returns default transport if none setting. Disable Auth config.
type Unmarshaler ¶
Unmarshaler is the interface implemented by types that can unmarshal themselves from bytes.
type UnmarshalerFrom ¶
UnmarshalerFrom is the interface implemented by types that can unmarshal themselves from body reader. The body underlying implementation is a *io.LimitedReader.
type ValueGetter ¶
ValueGetter fill argument's field from url values or http params.