httpx

package
v1.3.36 Latest Latest
Warning

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

Go to latest
Published: Apr 12, 2024 License: MIT Imports: 33 Imported by: 0

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,
		Format: `{"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}}` + "\n",
		CustomTimeFormat: "2006-01-02 15:04:05.00000",
		Output:           os.Stdout,
		// 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

if not modified, return true

func CheckIfNoneMatch added in v1.3.31

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

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, timeout int) (*http.Response, error)

func HttpGetBody

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

func HttpPost

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

func HttpPostBody

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

func IsConnError

func IsConnError(err error) bool

func Logger added in v1.3.30

func Logger() echo.MiddlewareFunc

Logger returns a middleware that logs HTTP requests.

func LoggerWithConfig added in v1.3.30

func LoggerWithConfig(config LoggerConfig) echo.MiddlewareFunc

LoggerWithConfig returns a Logger middleware with config. See: `Logger()`.

func NewEtag added in v1.3.31

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

func NewProxyTransport

func NewProxyTransport(proxyHost string, proxyPort int, isHttp bool) (*http.Transport, error)

func QueryMustParam

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

func QueryOptionalParam

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

func RegisterHandle

func RegisterHandle(funcGetECodeSuccess, funcGetECodeInternalError, funcGetECodeBadRequest func() int,
	funcErrToECode, funcErrToHttpStatus func(error) int,
	funcECodeToStr func(int) string,
	funcNewRequestId func() string)

func ResponseToMap

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

func ResultResp

func ResultResp(status, code int, result 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 StatusResp

func StatusResp(status int) error

func SuccessResp

func SuccessResp(result interface{}) error

func ValidateMust

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

func Wrap

func Wrap(err error) error

Types

type ApiGateway

type ApiGateway struct {
	Echo        *echo.Echo
	Logger      *logrus.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 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 HttpClient

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

func NewHttpClient

func NewHttpClient(transport http.RoundTripper) *HttpClient

func NewProxyClient

func NewProxyClient(proxyHost string, proxyPort int, isHttp bool) (*HttpClient, error)

func (*HttpClient) Get

func (pc *HttpClient) Get(url string, out io.Writer) (*Stats, error)

func (*HttpClient) GetAndDrop

func (pc *HttpClient) GetAndDrop(url string) (*Stats, error)

func (*HttpClient) PostJson

func (pc *HttpClient) PostJson(url string, obj interface{}) (*Stats, error)

func (*HttpClient) Purge

func (pc *HttpClient) Purge(url string) (*Stats, error)

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 {
	RequestId *string `json:"RequestId,omitempty"`
	Status    int     `json:"-"`
	Code      *string `json:"Code,omitempty"`
	CodeInt   *int    `json:"CodeInt,omitempty"`
	Message   *string `json:"Message,omitempty"`
	Result    any     `json:"Result,omitempty"`
	// contains filtered or unexported fields
}

func ErrStrResp

func ErrStrResp(status, code int, format string, a ...any) *JsonResponse

func ErrorResp

func ErrorResp(status, code int, err error) *JsonResponse

func (*JsonResponse) Error

func (e *JsonResponse) Error() string

func (*JsonResponse) IsNoContent

func (e *JsonResponse) IsNoContent() bool

func (*JsonResponse) String added in v1.3.30

func (e *JsonResponse) String() string

func (*JsonResponse) Unwrap

func (e *JsonResponse) Unwrap() error

type LogConfig

type LogConfig struct {
	LogFile        log.FileConfig
	Level          string `vx_default:"info"`
	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)
	ContentFormat string `` /* 133-byte string literal not displayed */
}

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.
	Format string `yaml:"format"`

	// 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