restyss

package module
v0.0.0-...-0170f92 Latest Latest
Warning

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

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

README

restyss

resty for server side

Documentation

Index

Constants

View Source
const (
	DefaultClientName      = ""
	DefaultRequestHookName = ""
)
View Source
const (
	// MockSwitchHeaderKey httpx的客户端设定MockerTransport后,会对携带X-Httpx-Mock: true头的请求进入mock处理过程
	MockSwitchHeaderKey = "X-Httpx-Mock"

	// MockTagHeaderKey httpx的客户端设定MockerTransport后,根据外部传入Tag控制Mock匹配逻辑
	MockTagHeaderKey = "X-Httpx-Mock-Tag"

	// MockResponseHeaderKey 用于确认响应是mock
	MockResponseHeaderKey = "X-Httpx-Mock-Response"
)

Variables

View Source
var ConstAlias = map[string]string{
	"req.host":              "host",
	"res.status_code":       "status_code",
	"req.method":            "method",
	"req.uri":               "request",
	"req.rt":                "rt",
	"req.header.user-agent": "user-agent",
	"res.header.pvlost":     "pvlost",
	"res.header.app-code":   "errcode",
}
View Source
var ConstFields = []string{
	"req.host", "req.uri", "req.method", "req.rt", "res.status_code", "error",
}

Functions

func Contains

func Contains(list []string, elem string) bool

Contains check if element in list, used to test

func DefaultRequestHook

func DefaultRequestHook(request *resty.Request, options *RequestOptions) error

func GetCookieByName

func GetCookieByName(cookie []*http.Cookie, name string) string

GetCookieByName 根据指定name获取cookie值

func MakeRestyRetryPolicy

func MakeRestyRetryPolicy(options RetryOptions) resty.RetryConditionFunc

MakeRestyRetryPolicy httpx的resty v2的重试策略函数生成器

func MarkReqStartAt

func MarkReqStartAt(client *resty.Client, req *resty.Request) error

MarkReqStartAt 记录请求开始时间, OnBeforeReqeust函数入参

func New

func New(opts ...Option) *resty.Client

New is a convenient utility function to create a go-resty v2 client

func NewServerRequest

func NewServerRequest(method, target string, body io.Reader) (*http.Request, error)

NewServerRequest returns a new incoming server Request, suitable for passing to an http.Handler for testing.

The target is the RFC 7230 "request-target": it may be either a path or an absolute URL. If target is an absolute URL, the host name from the URL is used. Otherwise, "example.com" is used.

The TLS field is set to a non-nil dummy value if target has scheme "https".

The Request.Proto is always HTTP/1.1.

An empty method means "GET".

The provided body may be nil. If the body is of type *bytes.Reader, *strings.Reader, or *bytes.Buffer, the Request.ContentLength is set.

To generate a client HTTP request instead of a server request, see the NewRequest function in the net/http package.

func NewServerRequestFromClient

func NewServerRequestFromClient(cr *http.Request) (*http.Request, error)

NewServerRequestFromClient convert client outgoing http request to server incoming request

func R

func R(ps ...any) *resty.Request

R create a new request

func ServerHeadersRequestMiddleware

func ServerHeadersRequestMiddleware(c *resty.Client, rq *resty.Request) error

ProxySetHeadersRequestMiddleware 自动从context提取CtxServerHeadersKey指定的headers并透明传递

func TransportWrapperChain

func TransportWrapperChain(wrappers ...TransportWrapper) http.RoundTripper

TransportWrapperChain is a helper function for composing TransportWrappers. Requests will traverse them in the order they're declared. That is, the first TransportWrapper is treated as the outermost TransportWrapper.

Types

type AccessLogger

type AccessLogger struct {
	Fields       []string          `json:"fields"`
	Alias        map[string]string `json:"alias"`
	MaxPrintSize int               `json:"max_print_size"`
	WhiteListUri []string          `json:"white_list_uri"`
	BlackListUri []string          `json:"black_list_uri"`

	Logger *zap.Logger
	// contains filtered or unexported fields
}

AccessLogger http client access log middleware

func NewAccessLogger

func NewAccessLogger(logger *zap.Logger, fields []string) *AccessLogger

func (*AccessLogger) ErrorMiddleware

func (a *AccessLogger) ErrorMiddleware() resty.ErrorHook

ErrorMiddleware error middleware

func (*AccessLogger) IsAllowUri

func (a *AccessLogger) IsAllowUri(uri string) bool

IsAllowUri to judge if print the log

func (*AccessLogger) ResponseMiddleware

func (a *AccessLogger) ResponseMiddleware() resty.ResponseMiddleware

ResponseMiddleware response middleware

func (*AccessLogger) SetAlias

func (a *AccessLogger) SetAlias(alias map[string]string) *AccessLogger

type Builder

type Builder struct {
	Name                  string            `json:"name"`
	RestyV2Name           string            `json:"resty_v2_name"`
	URL                   string            `json:"url"`
	Method                string            `json:"method"`
	Headers               map[string]string `json:"headers"`
	QueryParams           map[string]string `json:"query_params"`
	QueryParamsFromValues url.Values        `json:"query_params_from_values"`
	Form                  map[string]string `json:"form_data"`
	FormDataFromValues    url.Values        `json:"form_data_from_values"`
	MultipartFormData     map[string]string `json:"multipart_form_data"`
	PathParams            map[string]string `json:"path_params"`
	QueryString           string            `json:"query_string"`
	SRVDomain             string            `json:"srv_domain"`
	SRVService            string            `json:"srv_service"`
	Body                  string            `json:"body"`
	*Pager                `json:"pager"`
	// contains filtered or unexported fields
}

Builder 请求构造器

func (*Builder) Build

func (b *Builder) Build() (*resty.Request, error)

Build 构建请求

func (*Builder) Provision

func (b *Builder) Provision() error

Provision 初始化,非线程安全

func (*Builder) Request

func (b *Builder) Request(opts ...RequestOptionRestyV2) (*resty.Response, error)

Request 执行请求

func (*Builder) RequestAllPages

func (b *Builder) RequestAllPages(opts ...RequestOptionRestyV2) ([]*resty.Response, error)

RequestAllPages 根据Pager分页顺序请求所有页

func (*Builder) RequestOptions

func (b *Builder) RequestOptions() ([]RequestOptionRestyV2, error)

RequestOptions 返回请求属性配置函数列表

type CtxHeaderKey

type CtxHeaderKey string

CtxHeaderKey 用于服务端和客户端之间传递特定请求头 - 上下文注入:通过`http.handlers.context`完成服务请求头注入 - 上下文传递:http.Handler中通过restyss.GetRestyV2("xxx").R().SetContext(r.Contxt())....传递上下文 - 上下文提取:restyss.Client在相关的中间件内提取上下文是否包含特定信息执行特定逻辑 Note: 通常用于此头信息不应透传到上游服务,仅通过Context传递和使用,如果可以或应该传递给上游,使用CtxServerHeadersKey即可

type CtxKeyReqStartAt

type CtxKeyReqStartAt struct{}

type CtxResponseWriterKey

type CtxResponseWriterKey struct{}

CtxResponseWriterKey 用于服务端和客户端之间传递ResponseWriter

type CtxServerHeadersKey

type CtxServerHeadersKey struct{}

CtxServerHeadersKey 用于服务端和上游之间透传的请求头

type FormParser

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

func NewFormParser

func NewFormParser(raw interface{}) *FormParser

func (*FormParser) Get

func (f *FormParser) Get(key string) interface{}

Get 获取指定字段内容

func (*FormParser) GetRaw

func (f *FormParser) GetRaw() string

GetRaw 获取原始内容

type JSONParser

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

func NewJSONParser

func NewJSONParser(d interface{}) *JSONParser

func (*JSONParser) Get

func (j *JSONParser) Get(key string) interface{}

Get 获取指定字段内容

func (*JSONParser) GetRaw

func (j *JSONParser) GetRaw() string

GetRaw 获取原始内容

type MockerTransport

type MockerTransport struct {
	Matcher   mock.Matcher
	Transport http.RoundTripper

	// Expiration is the cache expiration time.
	// Default expiration is 1 hour.
	Expiration time.Duration
	// contains filtered or unexported fields
}

MockerTransport 带mock逻辑的Transport,即如果匹配Mock配置则返回mock响应,不匹配返回真实响应

func NewMockerTransport

func NewMockerTransport(matcher mock.Matcher, cache *cache.Codec, opts ...MockerTransportOption) *MockerTransport

NewMockerTransport 新建MockerTransport

func (*MockerTransport) Provision

func (mt *MockerTransport) Provision() error

func (*MockerTransport) RoundTrip

func (mt *MockerTransport) RoundTrip(rq *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper. 1. 识别动态开关 2. 拦截请求,计算eigenkey 3. 从cache获取响应,如果没有 4. 获取mocker,生成mock响应,缓存mock响应

func (*MockerTransport) SetRoundTripper

func (mt *MockerTransport) SetRoundTripper(rt http.RoundTripper)

type MockerTransportOption

type MockerTransportOption func(*MockerTransport)

MockerTransportOption MockerTransport属性设定函数

func WithExpiration

func WithExpiration(v time.Duration) MockerTransportOption

WithExpiration 设定mock响应的过期时间

func WithTransport

func WithTransport(v *http.Transport) MockerTransportOption

WithTransport 设定正常逻辑的Transport

type Option

type Option func(*Options)

Option stands for func used to modify Options

func WithAccessLogger

func WithAccessLogger(logger *AccessLogger) Option

WithAccessLogger set the *AccessLogger

func WithCookieJar

func WithCookieJar(jar *cookiejar.Jar) Option

WithCookieJar used to set cookiejar option

func WithDialContextFuncName

func WithDialContextFuncName(fnName string) Option

WithDialContextFuncName set dial context func name

func WithIdempotentMethods

func WithIdempotentMethods(methods ...string) Option

WithIdempotentMethods set the retriable idempotent methods list

func WithIdleConnTimeout

func WithIdleConnTimeout(d time.Duration) Option

WithIdleConnTimeout set the IdleConnTimeout

func WithMaxConnsPerHost

func WithMaxConnsPerHost(c int) Option

WithMaxConnsPerHost set the max connections per host

func WithMaxIdleConns

func WithMaxIdleConns(c int) Option

WithMaxIdleConns set the max idle connections

func WithMaxIdleConnsPerHost

func WithMaxIdleConnsPerHost(c int) Option

WithMaxIdleConnsPerHost set the max idle connections per host

func WithMaxWatiTime

func WithMaxWatiTime(d time.Duration) Option

WithMaxWatiTime set the max wait time

func WithNoOfRedirect

func WithNoOfRedirect(c int) Option

WithNoOfRedirect set the redirect limit

func WithNoRetryErrors

func WithNoRetryErrors(errs ...error) Option

WithNoRetryErrors set the not retriable errors list

func WithNoRetryErrorsRegexps

func WithNoRetryErrorsRegexps(regexps ...string) Option

WithNoRetryErrorsRegexps set the not retriable error regexps list

func WithRequestMiddlewareNames

func WithRequestMiddlewareNames(names []string) Option

WithRequestMiddlewareNames set the RequestMiddlewareNames

func WithResponseMiddlewareNames

func WithResponseMiddlewareNames(names []string) Option

WithResponseMiddlewareNames set the ResponseMiddlewareNames

func WithRetryCount

func WithRetryCount(c int) Option

WithRetryCount set the retry count

func WithStatusCode

func WithStatusCode(c int) Option

WithStatusCode set the retry status code

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout set the timeout

func WithWatiTime

func WithWatiTime(d time.Duration) Option

WithWatiTime set the wait time

type Options

type Options struct {
	Timeout      time.Duration
	NoOfRedirect int
	RetryCount   int
	WaitTime     time.Duration
	MaxWaitTime  time.Duration
	// NOTE:StatusCode 含义是大于此值的Response会被重试
	// The only HTTP codes which is valid for retry are 408, 502, 503 and 504?
	StatusCode              int
	CookieJar               *cookiejar.Jar
	IdempotentMethods       []string
	RequestMiddlewareNames  []string
	ResponseMiddlewareNames []string
	DialContextFuncName     string
	MaxIdleConns            *int
	MaxIdleConnsPerHost     *int
	MaxConnsPerHost         *int
	IdleConnTimeout         *time.Duration
	NoRetryErrors           []error
	NoRetryErrorRegexps     []string
	AccessLogger            *AccessLogger
}

Options stands for resty client options

func (Options) RetryOptions

func (options Options) RetryOptions() RetryOptions

RetryOptions 返回RetryOptions

type Pager

type Pager struct {
	PageIndexParamName string `json:"page_index_param_name"`
	PageSizeParamName  string `json:"page_size_param_name"`
	TotalGJSONPath     string `json:"total_gjson_path"`
	PageSize           uint   `json:"page_size"`
	InitialPageIndex   uint   `json:"initial_page_index"`
}

Pager 分页控制器

type Parser

type Parser interface {
	Get(key string) interface{}
	GetRaw() string
}

type RequestHook

type RequestHook func(*resty.Request, *RequestOptions) error

RequestHook used to custom request with external input

type RequestOption

type RequestOption func(*RequestOptions)

func AppendRequestHook

func AppendRequestHook(name string) RequestOption

func WithClientName

func WithClientName(name string) RequestOption

func WithExtestion

func WithExtestion(k string, v any) RequestOption

func WithRequestHookNames

func WithRequestHookNames(names []string) RequestOption

func WithServerRequest

func WithServerRequest(r *http.Request) RequestOption

type RequestOptionRestyV2

type RequestOptionRestyV2 func(*resty.Request)

RequestOptionRestyV2 Request选项

func WithBody

func WithBody(body interface{}) RequestOptionRestyV2

WithBody 设定请求体

func WithContext

func WithContext(ctx context.Context) RequestOptionRestyV2

WithContext 设定Context

func WithFormData

func WithFormData(params map[string]string) RequestOptionRestyV2

WithFormData 设定请求参数

func WithFormDataFromValues

func WithFormDataFromValues(params url.Values) RequestOptionRestyV2

WithFormDataFromValues 设定请求参数

func WithHeaders

func WithHeaders(headers map[string]string) RequestOptionRestyV2

WithHeaders 设定头

func WithMethod

func WithMethod(v string) RequestOptionRestyV2

WithMethod 设定method

func WithMultipartFormData

func WithMultipartFormData(params map[string]string) RequestOptionRestyV2

WithMultipartFormData 设定请求参数

func WithPathParams

func WithPathParams(params map[string]string) RequestOptionRestyV2

WithPathParams 设定请求参数

func WithQueryParams

func WithQueryParams(params map[string]string) RequestOptionRestyV2

WithQueryParams 设定请求参数

func WithQueryParamsFromValues

func WithQueryParamsFromValues(params url.Values) RequestOptionRestyV2

WithQueryParamsFromValues 设定请求参数

func WithQueryString

func WithQueryString(v string) RequestOptionRestyV2

WithQueryString 设定query string

func WithSRV

func WithSRV(domain, service string) RequestOptionRestyV2

WithSRV 设定请求参数

func WithURL

func WithURL(v string) RequestOptionRestyV2

WithURL 设定URL

type RequestOptions

type RequestOptions struct {
	ClientName       string
	RequestHookNames []string
	ServerRequest    *http.Request
	Extension        map[string]any
}

type RetryOptions

type RetryOptions struct {
	IdempotentMethods   []string
	NoRetryErrors       []error
	NoRetryErrorRegexps []string
	// contains filtered or unexported fields
}

RetryOptions 重试设定项

func (*RetryOptions) Provision

func (ro *RetryOptions) Provision() error

Provision 初始化

type TransportWrapper

type TransportWrapper interface {
	http.RoundTripper

	// SetRoundTripper set the underline http.RoundTripper of the wrapper, panic if error
	SetRoundTripper(http.RoundTripper)
}

Jump to

Keyboard shortcuts

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