rpc

package
v0.0.0-...-303e327 Latest Latest
Warning

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

Go to latest
Published: May 22, 2023 License: Apache-2.0 Imports: 32 Imported by: 0

Documentation

Index

Constants

View Source
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

View Source
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

View Source
const (
	GzipEncodingType = "gzip"
)

encoding

Variables

View Source
var ErrBodyReadTimeout = errors.New("read body timeout")

ErrBodyReadTimeout timeout error

View Source
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

func DetectError(err error) (int, string, error)

DetectError returns status code, error code, error

func DetectErrorCode

func DetectErrorCode(err error) string

DetectErrorCode returns error code

func DetectStatusCode

func DetectStatusCode(err error) int

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(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 ParseData

func ParseData(resp *http.Response, data interface{}) (err error)

ParseData parse response with data

func ParseResponseErr

func ParseResponseErr(resp *http.Response) (err error)

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 NewClient

func NewClient(cfg *Config) Client

NewClient returns a rpc client

func NewLbClient

func NewLbClient(cfg *LbConfig, sel Selector) Client

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) Abort

func (c *Context) Abort()

Abort the next handlers

func (*Context) AbortWithError

func (c *Context) AbortWithError(err error)

AbortWithError abort with error

func (*Context) AbortWithStatus

func (c *Context) AbortWithStatus(statusCode int)

AbortWithStatus abort with status

func (*Context) AbortWithStatusJSON

func (c *Context) AbortWithStatusJSON(statusCode int, obj interface{})

AbortWithStatusJSON abort with status and response data

func (*Context) ArgsBody

func (c *Context) ArgsBody(args interface{}) error

ArgsBody args in body

func (*Context) ArgsForm

func (c *Context) ArgsForm(args interface{}) error

ArgsForm args in form

func (*Context) ArgsPostForm

func (c *Context) ArgsPostForm(args interface{}) error

ArgsPostForm args in post form

func (*Context) ArgsQuery

func (c *Context) ArgsQuery(args interface{}) error

ArgsQuery args in query

func (*Context) ArgsURI

func (c *Context) ArgsURI(args interface{}) error

ArgsURI args in uri

func (*Context) Flush

func (c *Context) Flush()

Flush implements the http.Flush interface.

func (*Context) Get

func (c *Context) Get(key string) (val interface{}, exists bool)

Get returns the value for the given key, If the value does not exists it returns (nil, false).

func (*Context) Hijack

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

Hijack implements the http.Hijacker interface.

func (*Context) IsAborted

func (c *Context) IsAborted() bool

IsAborted return aborted or not

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) Pusher

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

Pusher implements the http.Pusher interface.

func (*Context) RemoteIP

func (c *Context) RemoteIP() (net.IP, bool)

RemoteIP parses the IP from Request.RemoteAddr, returns the net.IP (without the port).

func (*Context) RequestLength

func (c *Context) RequestLength() (int, error)

RequestLength read request body length

func (*Context) Respond

func (c *Context) Respond()

Respond response 200, and Content-Length: 0

func (*Context) RespondError

func (c *Context) RespondError(err error)

RespondError response error

func (*Context) RespondJSON

func (c *Context) RespondJSON(obj interface{})

RespondJSON response json

func (*Context) RespondStatus

func (c *Context) RespondStatus(statusCode int)

RespondStatus response status code

func (*Context) RespondStatusData

func (c *Context) RespondStatusData(statusCode int, obj interface{})

RespondStatusData response data with code

func (*Context) RespondWith

func (c *Context) RespondWith(statusCode int, contentType string, body []byte)

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

func (*Context) Set

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

Set is used to store a new key/value pair exclusively for this context.

func (*Context) Stream

func (c *Context) Stream(step func(w io.Writer) bool) bool

Stream sends a streaming response and returns a boolean indicates "Is client disconnected in middle of stream"

type Error

type Error struct {
	Status int    // http status code
	Code   string // error code
	Err    error  // error
}

Error implements HTTPError

func NewError

func NewError(statusCode int, errCode string, err error) *Error

NewError new error with

func (*Error) Error

func (e *Error) Error() string

Error implements error

func (*Error) ErrorCode

func (e *Error) ErrorCode() string

ErrorCode returns special defined code

func (*Error) StatusCode

func (e *Error) StatusCode() int

StatusCode returns http status code

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap errors.Is(), errors.As() and errors.Unwrap()

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

func Error2HTTPError(err error) HTTPError

Error2HTTPError returns an interface HTTPError from an error

type HandlerFunc

type HandlerFunc func(*Context)

HandlerFunc defines the handler of app function

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

type Marshaler interface {
	Marshal() ([]byte, string, error)
}

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

type MarshalerTo interface {
	MarshalTo(responseBody io.Writer) (string, error)
}

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 Option

type Option func(req *http.Request)

Option client options

func WithCrcEncode

func WithCrcEncode() Option

WithCrcEncode request with crc32 encode

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 New

func New() *Router

New alias of httprouter.New Return a Router, control by yourself

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 Selector

type Selector interface {
	// GetAvailableHosts get the available hosts
	GetAvailableHosts() []string
	// SetFail Mark host unavailable
	SetFail(string)
	// Close If use a background coroutine to enable the broken host, you can use it to close the coroutine
	Close()
}

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 OptArgsBody

func OptArgsBody() ServerOption

OptArgsBody argument in request body

func OptArgsForm

func OptArgsForm() ServerOption

OptArgsForm argument in form

func OptArgsPostForm

func OptArgsPostForm() ServerOption

OptArgsPostForm argument in post form

func OptArgsQuery

func OptArgsQuery() ServerOption

OptArgsQuery argument in query string

func OptArgsURI

func OptArgsURI() ServerOption

OptArgsURI argument in uri

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

type Unmarshaler interface {
	Unmarshal([]byte) error
}

Unmarshaler is the interface implemented by types that can unmarshal themselves from bytes.

type UnmarshalerFrom

type UnmarshalerFrom interface {
	UnmarshalFrom(requestBody io.Reader) error
}

UnmarshalerFrom is the interface implemented by types that can unmarshal themselves from body reader. The body underlying implementation is a *io.LimitedReader.

type ValueGetter

type ValueGetter func(string) string

ValueGetter fill argument's field from url values or http params.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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