httpx

package
v1.3.58 Latest Latest
Warning

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

Go to latest
Published: Aug 16, 2024 License: MIT Imports: 33 Imported by: 5

Documentation

Index

Constants

View Source
const (
	ERR_NONE     = "none"
	ERR_CONNTION = "Connection Error"
	ERR_READ     = "Read Content Error"
	ERR_REQ      = "Request Error"
	ERR_JSON     = "Encode/Decode json Error"
)
View Source
const (
	DefaultBodyBufferSize = 4096
)

Variables

View Source
var (
	// DefaultLoggerConfig is the default Logger middleware config.
	DefaultLoggerConfig = LoggerConfig{
		Skipper:       middleware.DefaultSkipper,
		OutBodyFilter: DefaultOutBodyFilter,
		FormatBefore: `{"time":"${time_rfc3339_nano}","id":"${id}","remote_ip":"${remote_ip}",` +
			`"host":"${host}","method":"${method}","uri":"${uri}","user_agent":"${user_agent}",` +
			`,"bytes_in":${bytes_in}`,
		FormatAfter: `{"time":"${time_rfc3339_nano}","id":"${id}","remote_ip":"${remote_ip}",` +
			`"host":"${host}","method":"${method}","uri":"${uri}","user_agent":"${user_agent}",` +
			`"status":${status},"error":"${error}","latency":${latency},"latency_human":"${latency_human}"` +
			`,"bytes_in":${bytes_in},"bytes_out":${bytes_out}}`,
		CustomTimeFormat: "2006-01-02 15:04:05.000",
		Output:           os.Stdout,

		Timing: AccessLogBoth,
		// contains filtered or unexported fields
	}
)
View Source
var ErrBadParams error = errors.New("Bad input params")
View Source
var StatsTotalReqs int64
View Source
var UserAgent string = "Json Http Client"

var ErrNot200OK error = errors.New("the response is not 200 OK")

Functions

func BindAndValidate

func BindAndValidate(c echo.Context, i any) error
BindAndValidate 提供从echo.Context里请求里Request的query parameter或者body里取相应的值,赋值给i,并做自校验。使用方式为

type Trans struct {
	Bandwidth uint64 `hx_place:"query" hx_must:"true" hx_query_name:"bandwidth" hx_default:"default_name" hx_range:"1-2"`
	Loss     float64 `hx_place:"body" hx_must:"false" hx_query_name:"loss" hx_default:"default_name" hx_range:"1.2,3.4"`
}

type TusReq struct {
	Name       string `hx_place:"query" hx_must:"true" hx_query_name:"host_name" hx_default:"default_name" hx_range:"alice,bob"`
	TaskId     int64  `hx_place:"body" hx_must:"false" hx_query_name:"task_id" hx_default:"7" hx_range:"0-21"`
	Transfer   Trans
}

hx_tag自定义如下:

  easy-to-read style: `hx_place:"query" hx_query_name:"name_in_query" hx_must:"true" hx_default:"def" hx_range:"1-20"
	hx_place: query表示该值从query parameter里取,body从请求body里取。
	hx_query_name: Query Parameters中定义的名称
	hx_must: true表示必须,若未赋值,则报错;false表示可选
	hx_default: 若未赋值,设为该默认值
	hx_range: 根据i的字段的类型来校验range:若为整数,0-21表示0到21是合法的,否则报错;若为字符串,"alice,bob"表示只能为alice或bob,否则报错。

  compact style:`hx_tag:"f1;f2;f3;f4;f5"`
	f1: same to hx_place
	f2: same to hx_query_name
	f3: same to hx_must
	f4: same to hx_default
	f5: same to hx_range

func CheckIfModifiedSince added in v1.3.31

func CheckIfModifiedSince(r *http.Request, modtime time.Time) bool

CheckIfModifiedSince if not modified, return true

func CheckIfNoneMatch added in v1.3.31

func CheckIfNoneMatch(r *http.Request, currentEtag string) bool

CheckIfNoneMatch if Etag same, true

func DefaultOutBodyFilter added in v1.3.30

func DefaultOutBodyFilter(echo.Context) bool

DefaultOutBodyFilter returns false which processes the middleware.

func GetRealIp

func GetRealIp(req *http.Request) string

func HttpGet

func HttpGet(url string) (*http.Response, error)

func HttpGetBody

func HttpGetBody(url string) (*http.Response, []byte, error)

func HttpPost

func HttpPost(url string, body interface{}) (*http.Response, error)

func HttpPostBody

func HttpPostBody(url string, body interface{}) (*http.Response, []byte, error)

func IsConnError

func IsConnError(err error) bool

func LoggerWithConfig added in v1.3.30

func LoggerWithConfig(config LoggerConfig) echo.MiddlewareFunc

func NewEtag added in v1.3.31

func NewEtag(modTime time.Time, length int64) string

func QueryMustParam

func QueryMustParam(c echo.Context, key string) (string, error)

func QueryOptionalParam

func QueryOptionalParam(c echo.Context, key string) (string, bool)

func RegisterErrCodeDictionary added in v1.3.39

func RegisterErrCodeDictionary(dic errcodex.ErrorCodeDictionaryIf)

func ResetDefaultClient added in v1.3.37

func ResetDefaultClient(hc *Client)

func ResponseToMap

func ResponseToMap(body []byte) (map[string]interface{}, error)

func SendResp

func SendResp(c echo.Context, resp error) (err error)

func ServeContent added in v1.3.31

func ServeContent(w http.ResponseWriter, req *http.Request, name string, modTime time.Time, length int64, content io.ReadSeeker)

func TrimHttpStatusText added in v1.3.48

func TrimHttpStatusText(status int) string

func ValidateMust

func ValidateMust(input interface{}, keys ...string) error

Types

type AccessLogTiming added in v1.3.48

type AccessLogTiming string
const (
	AccessLogBeforeRun AccessLogTiming = "before"
	AccessLogAfterRun  AccessLogTiming = "after"
	AccessLogBoth      AccessLogTiming = "both"
)

type ApiGateway

type ApiGateway struct {
	*echo.Echo
	Logger      *log.Logger
	LogConf     *LogConfig
	EntryFormat logrus.Formatter
	// contains filtered or unexported fields
}

func NewApiGateway

func NewApiGateway(pCtx context.Context, lc *LogConfig, logFormat logrus.Formatter) (*ApiGateway, error)

func (*ApiGateway) RoutesToString

func (agw *ApiGateway) RoutesToString() string

func (*ApiGateway) Run

func (agw *ApiGateway) Run(ip, port string) error

func (*ApiGateway) Stop

func (agw *ApiGateway) Stop() error

type AuthJsonClient

type AuthJsonClient struct {
	Client JsonClient
	// contains filtered or unexported fields
}

func (*AuthJsonClient) DelR

func (c *AuthJsonClient) DelR(url string, headers map[string]string) (*resty.Response, error)

func (*AuthJsonClient) Get

func (c *AuthJsonClient) Get(url string, headers map[string]string) (typex.JsonMap, error)

func (*AuthJsonClient) Login

func (c *AuthJsonClient) Login(method, url string, headers map[string]string,
	data interface{}, tokenField string) (string, error)

func (*AuthJsonClient) Post

func (c *AuthJsonClient) Post(url string, headers map[string]string, data interface{}) (typex.JsonMap, error)

func (*AuthJsonClient) Put

func (c *AuthJsonClient) Put(url string, headers map[string]string, data interface{}) (typex.JsonMap, error)

func (*AuthJsonClient) Request

func (c *AuthJsonClient) Request(method, url string, headers map[string]string,
	data interface{}) (typex.JsonMap, error)

func (*AuthJsonClient) RequestR

func (c *AuthJsonClient) RequestR(result interface{}, method, url string, headers map[string]string,
	data interface{}) (*resty.Response, error)

type Client added in v1.3.37

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

func WithTimeout added in v1.3.37

func WithTimeout(timeout int) *Client

func (*Client) HttpGet added in v1.3.37

func (hc *Client) HttpGet(url string) (*http.Response, error)

func (*Client) HttpGetBody added in v1.3.37

func (hc *Client) HttpGetBody(url string) (*http.Response, []byte, error)

func (*Client) HttpPost added in v1.3.37

func (hc *Client) HttpPost(url string, body interface{}) (*http.Response, error)

func (*Client) WithTimeout added in v1.3.37

func (hc *Client) WithTimeout(timeout int) *Client

type DropWriter

type DropWriter struct {
}

func (*DropWriter) Write

func (dw *DropWriter) Write(p []byte) (int, error)

type Filter added in v1.3.30

type Filter func(echo.Context) bool

type JsonClient

type JsonClient struct {
	IsHttps bool
	Host    string
	Port    int
	Timeout int // in milliseconds
	// contains filtered or unexported fields
}

func NewJsonClient

func NewJsonClient(host string, port int, timeout int) *JsonClient

func NewJsonClientWithRetry

func NewJsonClientWithRetry(host string, port, timeout, retryCount, retryWaitTime int) *JsonClient

func (*JsonClient) Client

func (c *JsonClient) Client() *resty.Client

func (*JsonClient) Del

func (c *JsonClient) Del(url string, headers map[string]string, data interface{}) (typex.JsonMap, error)

func (*JsonClient) DelR

func (c *JsonClient) DelR(url string, headers map[string]string) (*resty.Response, error)

func (*JsonClient) Get

func (c *JsonClient) Get(url string, headers map[string]string) (typex.JsonMap, error)

func (*JsonClient) GetR

func (c *JsonClient) GetR(url string, headers map[string]string) (*resty.Response, error)

func (*JsonClient) Post

func (c *JsonClient) Post(url string, headers map[string]string, data interface{}) (typex.JsonMap, error)

func (*JsonClient) PostR

func (c *JsonClient) PostR(url string, headers map[string]string, data interface{}) (*resty.Response, error)

func (*JsonClient) Put

func (c *JsonClient) Put(url string, headers map[string]string, data interface{}) (typex.JsonMap, error)

func (*JsonClient) PutR

func (c *JsonClient) PutR(url string, headers map[string]string, data interface{}) (*resty.Response, error)

func (*JsonClient) Request

func (c *JsonClient) Request(method, url string, headers map[string]string,
	data interface{}) (typex.JsonMap, error)

func (*JsonClient) RequestR

func (c *JsonClient) RequestR(result interface{}, method, url string, headers map[string]string,
	data interface{}) (*resty.Response, error)

func (*JsonClient) RequestTimeout

func (c *JsonClient) RequestTimeout(method, url string, headers map[string]string,
	data interface{}, timeout int) (typex.JsonMap, error)

func (*JsonClient) SetInsecure

func (c *JsonClient) SetInsecure()

func (*JsonClient) SetReuseConnection

func (c *JsonClient) SetReuseConnection()

func (*JsonClient) SetStatsChan

func (c *JsonClient) SetStatsChan(ch chan<- *RequestStats)

func (*JsonClient) SetTransport

func (c *JsonClient) SetTransport(maxIdleConns, maxIdleConnsPerHost int)

func (*JsonClient) StatusError

func (c *JsonClient) StatusError(method, url string, rsp *resty.Response) *StatusError

func (*JsonClient) Transport

func (c *JsonClient) Transport() http.RoundTripper

func (*JsonClient) Url

func (c *JsonClient) Url(api string) string

type JsonResponse

type JsonResponse struct {
	Status int `json:"-"`

	Code    string `json:"Code,omitempty"`
	Errno   int    `json:"Errno,omitempty"`
	Message string `json:"Message,omitempty"`

	RequestId string `json:"RequestId,omitempty"`
	Result    any    `json:"Result,omitempty"`
	// contains filtered or unexported fields
}

JsonResponse should be:

func PostX added in v1.3.48

func PostX(url string, reqBody interface{}, result interface{}) (*JsonResponse, error)

func StatusResp

func StatusResp(status int) *JsonResponse

func SuccessResp

func SuccessResp(result any) *JsonResponse

func Wrap

func Wrap(err error) *JsonResponse

wrap with JsonResponse, with Stack

func (*JsonResponse) Cause added in v1.3.49

func (jr *JsonResponse) Cause() error

Cause return children cause. will not recursively retrieve cause.Cause

func (*JsonResponse) Copy added in v1.3.52

func (jr *JsonResponse) Copy() *JsonResponse

func (*JsonResponse) Error

func (jr *JsonResponse) Error() string

Error output err at first, then Message, then flatErrString

func (*JsonResponse) Format added in v1.3.48

func (jr *JsonResponse) Format(s fmt.State, verb rune)

nolint: errcheck

func (*JsonResponse) GetCode added in v1.3.54

func (jr *JsonResponse) GetCode() string

func (*JsonResponse) GetErrno added in v1.3.54

func (jr *JsonResponse) GetErrno() int

func (*JsonResponse) GetHttpStatus added in v1.3.54

func (jr *JsonResponse) GetHttpStatus() int

func (*JsonResponse) Is added in v1.3.48

func (jr *JsonResponse) Is(target error) bool

return true while Code is same

func (*JsonResponse) IsOK added in v1.3.43

func (jr *JsonResponse) IsOK() bool

func (*JsonResponse) JsonString added in v1.3.48

func (jr *JsonResponse) JsonString() string

JsonString won't output

func (*JsonResponse) Unwrap

func (jr *JsonResponse) Unwrap() error

func (*JsonResponse) WithError added in v1.3.39

func (jr *JsonResponse) WithError(err error, depths ...int) *JsonResponse

WithError to be simple, do overwrite err, will impact IsOK()

func (*JsonResponse) WithErrorf added in v1.3.41

func (jr *JsonResponse) WithErrorf(format string, a ...any) error

WithErrorf to be simple, do overwrite err, will impact IsOK()

func (*JsonResponse) WithMessagef added in v1.3.53

func (jr *JsonResponse) WithMessagef(format string, a ...any) error

WithMessagef append Message, won't impact IsOK()

func (*JsonResponse) WithResult added in v1.3.39

func (jr *JsonResponse) WithResult(result any) *JsonResponse

WithResult to be simple, do overwrite

func (*JsonResponse) WithStack added in v1.3.49

func (jr *JsonResponse) WithStack(relativeDepths ...int) *JsonResponse

WithStack add cause with StackTrace

type LogConfig

type LogConfig struct {
	LogFile        log.FileConfig
	Level          string          `vx_default:"info"`
	Timing         AccessLogTiming `vx_default:"both"`
	BodyBufferSize int64           `vx_default:"4096"`
	// Tags to construct the Logger format.
	//
	// - time_unix
	// - time_unix_nano
	// - time_rfc3339
	// - time_rfc3339_nano
	// - time_custom
	// - id (Request ID)
	// - remote_ip
	// - uri
	// - host
	// - method
	// - path
	// - protocol
	// - referer
	// - user_agent
	// - status
	// - error
	// - latency (In nanoseconds)
	// - latency_human (Human readable)
	// - bytes_in (Bytes received)
	// - bytes_out (Bytes sent)
	// - header_in:<NAME>
	// - header_out:<NAME>
	// - query:<NAME>
	// - form:<NAME>
	// - body_in (request body)
	// - body_out (response body)
	//ContentFormatBefore string `vx_default:"${time_custom} BEF ${method} ${uri} ${host} ${remote_ip} ${bytes_in}"`
	ContentFormatBefore string
	//ContentFormatAfter  string `vx_default:"${time_custom} AFT ${status} ${method} ${latency_human} ${uri} ${host} ${remote_ip} ${bytes_in} ${bytes_out} ${error}"`
	ContentFormatAfter string
}

type LoggerConfig added in v1.3.30

type LoggerConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper middleware.Skipper

	// OutBodyFilter defines a function to print body_out, false by default due to additional memory used
	OutBodyFilter middleware.Skipper

	// Tags to construct the logger format.
	//
	// - time_unix
	// - time_unix_nano
	// - time_rfc3339
	// - time_rfc3339_nano
	// - time_custom
	// - id (Request ID)
	// - remote_ip
	// - uri
	// - host
	// - method
	// - path
	// - protocol
	// - referer
	// - user_agent
	// - status
	// - error
	// - latency (In nanoseconds)
	// - latency_human (Human readable)
	// - bytes_in (Bytes received)
	// - bytes_out (Bytes sent)
	// - header_in:<NAME>
	// - header_out:<NAME>
	// - query:<NAME>
	// - form:<NAME>
	// - body_in (request body)
	// - body_out (response body)   , should also define OutBodyFilter to log only necessary.
	//
	// Example "${remote_ip} ${status}"
	//
	// Optional. Default value DefaultLoggerConfig.Format.
	FormatAfter  string `yaml:"format_after"`
	FormatBefore string `yaml:"format_before"`
	Timing       AccessLogTiming

	// Optional. Default value DefaultLoggerConfig.CustomTimeFormat.
	CustomTimeFormat string `yaml:"custom_time_format"`

	// Output is a writer where logs in JSON format are written.
	// Optional. Default value os.Stdout.
	Output io.Writer
	// contains filtered or unexported fields
}

LoggerConfig defines the config for Logger middleware.

type RequestStats

type RequestStats struct {
	Scheme   string
	Host     string
	Port     int
	Uri      string
	Method   string
	ReqTime  time.Time
	SendTime time.Time
	RspTime  time.Time
	Latency  int64
	PreTime  int64
	Status   int
}

format := "${time_rfc3339} ${time_unix} ${status} ${method} ${latency} ${remote_ip} ${bytes_in} ${bytes_out} ${uri}\n"

func (*RequestStats) LogLine

func (s *RequestStats) LogLine() string

type RoundrobinClient

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

func NewRoundrobinClient

func NewRoundrobinClient(service string, https bool, hosts []string, port int,
	sign *auth.SignCfg, apiTimeout, retryTime int) *RoundrobinClient

func NewRoundrobinClient2

func NewRoundrobinClient2(service string, cl []*JsonClient, sign *auth.SignCfg, retryTime int) *RoundrobinClient

func (*RoundrobinClient) Client

func (c *RoundrobinClient) Client() *JsonClient

func (*RoundrobinClient) DelR

func (c *RoundrobinClient) DelR(url string, headers map[string]string) (*resty.Response, error)

func (*RoundrobinClient) Get

func (c *RoundrobinClient) Get(url string, headers map[string]string) (typex.JsonMap, error)

func (*RoundrobinClient) GetR

func (c *RoundrobinClient) GetR(url string, headers map[string]string) (*resty.Response, error)

func (*RoundrobinClient) Post

func (c *RoundrobinClient) Post(url string, headers map[string]string, data interface{}) (typex.JsonMap, error)

func (*RoundrobinClient) PostR

func (c *RoundrobinClient) PostR(url string, headers map[string]string, data interface{}) (*resty.Response, error)

func (*RoundrobinClient) Put

func (c *RoundrobinClient) Put(url string, headers map[string]string, data interface{}) (typex.JsonMap, error)

func (*RoundrobinClient) PutR

func (c *RoundrobinClient) PutR(url string, headers map[string]string, data interface{}) (*resty.Response, error)

func (*RoundrobinClient) Request

func (c *RoundrobinClient) Request(method, url string, headers map[string]string,
	data interface{}) (typex.JsonMap, error)

func (*RoundrobinClient) RequestR

func (c *RoundrobinClient) RequestR(result interface{}, method, url string, headers map[string]string, data interface{}) (*resty.Response, error)

light wrapper of RoundrobinClient.RequestR

func (*RoundrobinClient) SetInsecure

func (c *RoundrobinClient) SetInsecure()

func (*RoundrobinClient) SetReuseConnection

func (c *RoundrobinClient) SetReuseConnection()

must called before any request

func (*RoundrobinClient) SetTransport

func (c *RoundrobinClient) SetTransport(maxIdleConns, maxIdleConnsPerHost int)

must called before any request

func (*RoundrobinClient) StatusError

func (c *RoundrobinClient) StatusError(method, api string, rsp *resty.Response) *StatusError

func (*RoundrobinClient) Url

func (c *RoundrobinClient) Url(api string) string

type RrServer

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

type Stats

type Stats struct {
	Error         string
	Url           string
	Status        int
	Proto         string
	ContentLength int64
	DownloadSize  int64
	TimeToServe   float64 // in seconds
	RespHeader    http.Header
	Resp          *http.Response
}

func NewStats

func NewStats() *Stats

type StatusError

type StatusError struct {
	Err    string
	Status int
	Rsp    *resty.Response
}

func NewStatusError

func NewStatusError(method, host, api string, rsp *resty.Response) *StatusError

func NewStatusError2

func NewStatusError2(method, url string, rsp *resty.Response) *StatusError

func (*StatusError) Body

func (e *StatusError) Body() string

func (*StatusError) Error

func (e *StatusError) Error() string

Jump to

Keyboard shortcuts

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