86 lines
2.0 KiB
Go
86 lines
2.0 KiB
Go
|
package httpcall
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"finclip-app-manager/infrastructure/logger"
|
||
|
"github.com/go-resty/resty/v2"
|
||
|
"gitlab.finogeeks.club/finclip-backend/apm"
|
||
|
"net"
|
||
|
"net/http"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
|
const (
|
||
|
ErrConnection = "Connection failed"
|
||
|
ErrHttpCode = "Unexpected http response code"
|
||
|
ErrResponseFormat = "Invalid response format"
|
||
|
ErrSystemCall = "System call error"
|
||
|
ErrEmptyURL = "Empty URL"
|
||
|
)
|
||
|
|
||
|
var (
|
||
|
log = logger.GetLogger()
|
||
|
defaultReqHeader = map[string]string{
|
||
|
"Accept": "application/json, text/plain, */*",
|
||
|
"Content-Type": "application/json",
|
||
|
"url-call": "internal",
|
||
|
}
|
||
|
restyClient = resty.NewWithClient(&http.Client{
|
||
|
Transport: createTransport(nil),
|
||
|
})
|
||
|
)
|
||
|
|
||
|
type ErrInfo struct {
|
||
|
Errcode string `json:"errcode"`
|
||
|
Error string `json:"error"`
|
||
|
}
|
||
|
|
||
|
type Client struct{}
|
||
|
|
||
|
func NewClient() *Client {
|
||
|
return &Client{}
|
||
|
}
|
||
|
|
||
|
func (c *Client) Request(ctx context.Context) *resty.Request {
|
||
|
return restyClient.R().SetContext(ctx)
|
||
|
}
|
||
|
|
||
|
func (c *Client) getNewDefaultReqHeader() map[string]string {
|
||
|
newReqHeader := make(map[string]string)
|
||
|
for k, v := range defaultReqHeader {
|
||
|
newReqHeader[k] = v
|
||
|
}
|
||
|
return newReqHeader
|
||
|
}
|
||
|
|
||
|
func createTransport(localAddr net.Addr) http.RoundTripper {
|
||
|
dialer := &net.Dialer{
|
||
|
Timeout: 30 * time.Second,
|
||
|
KeepAlive: 30 * time.Second,
|
||
|
}
|
||
|
if localAddr != nil {
|
||
|
dialer.LocalAddr = localAddr
|
||
|
}
|
||
|
return &apmRetryTransport{&http.Transport{
|
||
|
Proxy: http.ProxyFromEnvironment,
|
||
|
DialContext: dialer.DialContext,
|
||
|
MaxIdleConns: 200,
|
||
|
IdleConnTimeout: 90 * time.Second,
|
||
|
TLSHandshakeTimeout: 10 * time.Second,
|
||
|
ExpectContinueTimeout: 1 * time.Second,
|
||
|
MaxIdleConnsPerHost: 200,
|
||
|
}}
|
||
|
}
|
||
|
|
||
|
type apmRetryTransport struct {
|
||
|
*http.Transport
|
||
|
}
|
||
|
|
||
|
func (transport *apmRetryTransport) RoundTrip(request *http.Request) (*http.Response, error) {
|
||
|
eSpan := apm.ApmClient().CreateHttpExitSpan(request.Context(), request, request.URL.Host, request.URL.Path)
|
||
|
defer eSpan.End()
|
||
|
|
||
|
resp, err := transport.Transport.RoundTrip(request)
|
||
|
return resp, err
|
||
|
}
|