Documentation ¶
Index ¶
- Constants
- Variables
- func BindAndValidate(c echo.Context, i any) error
- func CheckIfModifiedSince(r *http.Request, modtime time.Time) bool
- func CheckIfNoneMatch(r *http.Request, currentEtag string) bool
- func DefaultOutBodyFilter(echo.Context) bool
- func GetRealIp(req *http.Request) string
- func HttpGet(url string) (*http.Response, error)
- func HttpGetBody(url string) (*http.Response, []byte, error)
- func HttpPost(url string, body interface{}) (*http.Response, error)
- func HttpPostBody(url string, body interface{}) (*http.Response, []byte, error)
- func IsConnError(err error) bool
- func LoggerWithConfig(config LoggerConfig) echo.MiddlewareFunc
- func NewEtag(modTime time.Time, length int64) string
- func QueryMustParam(c echo.Context, key string) (string, error)
- func QueryOptionalParam(c echo.Context, key string) (string, bool)
- func RegisterErrCodeDictionary(dic errcodex.ErrorCodeDictionaryIf)
- func ResetDefaultClient(hc *Client)
- func ResponseToMap(body []byte) (map[string]interface{}, error)
- func SendResp(c echo.Context, resp error) (err error)
- func ServeContent(w http.ResponseWriter, req *http.Request, name string, modTime time.Time, ...)
- func TrimHttpStatusText(status int) string
- func ValidateMust(input interface{}, keys ...string) error
- type AccessLogTiming
- type ApiGateway
- type AuthJsonClient
- func (c *AuthJsonClient) DelR(url string, headers map[string]string) (*resty.Response, error)
- func (c *AuthJsonClient) Get(url string, headers map[string]string) (typex.JsonMap, error)
- func (c *AuthJsonClient) Login(method, url string, headers map[string]string, data interface{}, ...) (string, error)
- func (c *AuthJsonClient) Post(url string, headers map[string]string, data interface{}) (typex.JsonMap, error)
- func (c *AuthJsonClient) Put(url string, headers map[string]string, data interface{}) (typex.JsonMap, error)
- func (c *AuthJsonClient) Request(method, url string, headers map[string]string, data interface{}) (typex.JsonMap, error)
- func (c *AuthJsonClient) RequestR(result interface{}, method, url string, headers map[string]string, ...) (*resty.Response, error)
- type Client
- type DropWriter
- type Filter
- type JsonClient
- func (c *JsonClient) Client() *resty.Client
- func (c *JsonClient) Del(url string, headers map[string]string, data interface{}) (typex.JsonMap, error)
- func (c *JsonClient) DelR(url string, headers map[string]string) (*resty.Response, error)
- func (c *JsonClient) Get(url string, headers map[string]string) (typex.JsonMap, error)
- func (c *JsonClient) GetR(url string, headers map[string]string) (*resty.Response, error)
- func (c *JsonClient) Post(url string, headers map[string]string, data interface{}) (typex.JsonMap, error)
- func (c *JsonClient) PostR(url string, headers map[string]string, data interface{}) (*resty.Response, error)
- func (c *JsonClient) Put(url string, headers map[string]string, data interface{}) (typex.JsonMap, error)
- func (c *JsonClient) PutR(url string, headers map[string]string, data interface{}) (*resty.Response, error)
- func (c *JsonClient) Request(method, url string, headers map[string]string, data interface{}) (typex.JsonMap, error)
- func (c *JsonClient) RequestR(result interface{}, method, url string, headers map[string]string, ...) (*resty.Response, error)
- func (c *JsonClient) RequestTimeout(method, url string, headers map[string]string, data interface{}, timeout int) (typex.JsonMap, error)
- func (c *JsonClient) SetInsecure()
- func (c *JsonClient) SetReuseConnection()
- func (c *JsonClient) SetStatsChan(ch chan<- *RequestStats)
- func (c *JsonClient) SetTransport(maxIdleConns, maxIdleConnsPerHost int)
- func (c *JsonClient) StatusError(method, url string, rsp *resty.Response) *StatusError
- func (c *JsonClient) Transport() http.RoundTripper
- func (c *JsonClient) Url(api string) string
- type JsonResponse
- func (jr *JsonResponse) Cause() error
- func (jr *JsonResponse) Copy() *JsonResponse
- func (jr *JsonResponse) Error() string
- func (jr *JsonResponse) Format(s fmt.State, verb rune)
- func (jr *JsonResponse) GetCode() string
- func (jr *JsonResponse) GetErrno() int
- func (jr *JsonResponse) GetHttpStatus() int
- func (jr *JsonResponse) Is(target error) bool
- func (jr *JsonResponse) IsOK() bool
- func (jr *JsonResponse) JsonString() string
- func (jr *JsonResponse) Unwrap() error
- func (jr *JsonResponse) WithError(err error, depths ...int) *JsonResponse
- func (jr *JsonResponse) WithErrorf(format string, a ...any) error
- func (jr *JsonResponse) WithMessagef(format string, a ...any) error
- func (jr *JsonResponse) WithResult(result any) *JsonResponse
- func (jr *JsonResponse) WithStack(relativeDepths ...int) *JsonResponse
- type LogConfig
- type LoggerConfig
- type RequestStats
- type RoundrobinClient
- func (c *RoundrobinClient) Client() *JsonClient
- func (c *RoundrobinClient) DelR(url string, headers map[string]string) (*resty.Response, error)
- func (c *RoundrobinClient) Get(url string, headers map[string]string) (typex.JsonMap, error)
- func (c *RoundrobinClient) GetR(url string, headers map[string]string) (*resty.Response, error)
- func (c *RoundrobinClient) Post(url string, headers map[string]string, data interface{}) (typex.JsonMap, error)
- func (c *RoundrobinClient) PostR(url string, headers map[string]string, data interface{}) (*resty.Response, error)
- func (c *RoundrobinClient) Put(url string, headers map[string]string, data interface{}) (typex.JsonMap, error)
- func (c *RoundrobinClient) PutR(url string, headers map[string]string, data interface{}) (*resty.Response, error)
- func (c *RoundrobinClient) Request(method, url string, headers map[string]string, data interface{}) (typex.JsonMap, error)
- func (c *RoundrobinClient) RequestR(result interface{}, method, url string, headers map[string]string, ...) (*resty.Response, error)
- func (c *RoundrobinClient) SetInsecure()
- func (c *RoundrobinClient) SetReuseConnection()
- func (c *RoundrobinClient) SetTransport(maxIdleConns, maxIdleConnsPerHost int)
- func (c *RoundrobinClient) StatusError(method, api string, rsp *resty.Response) *StatusError
- func (c *RoundrobinClient) Url(api string) string
- type RrServer
- type Stats
- type StatusError
Constants ¶
const ( ERR_NONE = "none" ERR_CONNTION = "Connection Error" ERR_READ = "Read Content Error" ERR_REQ = "Request Error" ERR_JSON = "Encode/Decode json Error" )
const (
DefaultBodyBufferSize = 4096
)
Variables ¶
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 } )
var ErrBadParams error = errors.New("Bad input params")
var StatsTotalReqs int64
var UserAgent string = "Json Http Client"
var ErrNot200OK error = errors.New("the response is not 200 OK")
Functions ¶
func BindAndValidate ¶
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
CheckIfModifiedSince if not modified, return true
func CheckIfNoneMatch ¶ added in v1.3.31
CheckIfNoneMatch if Etag same, true
func DefaultOutBodyFilter ¶ added in v1.3.30
DefaultOutBodyFilter returns false which processes the middleware.
func IsConnError ¶
func LoggerWithConfig ¶ added in v1.3.30
func LoggerWithConfig(config LoggerConfig) echo.MiddlewareFunc
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 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 ValidateMust ¶
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 (*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 }
type Client ¶ added in v1.3.37
type Client struct {
// contains filtered or unexported fields
}
func WithTimeout ¶ added in v1.3.37
func (*Client) HttpGetBody ¶ added in v1.3.37
func (*Client) WithTimeout ¶ added in v1.3.37
type DropWriter ¶
type DropWriter struct { }
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) RequestTimeout ¶
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 (*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 NewRoundrobinClient2 ¶
func NewRoundrobinClient2(service string, cl []*JsonClient, sign *auth.SignCfg, retryTime int) *RoundrobinClient
func (*RoundrobinClient) Client ¶
func (c *RoundrobinClient) Client() *JsonClient
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 Stats ¶
type StatusError ¶
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