58 lines
1011 B
Go
58 lines
1011 B
Go
package util
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"sync"
|
|
)
|
|
|
|
type HttpClient struct {
|
|
client *http.Client
|
|
once sync.Once
|
|
}
|
|
|
|
func NewHttpClient() *HttpClient {
|
|
return &HttpClient{
|
|
http.DefaultClient,
|
|
sync.Once{},
|
|
}
|
|
}
|
|
|
|
func (h *HttpClient) getClient() *http.Client {
|
|
h.once.Do(func() {
|
|
h.client = &http.Client{}
|
|
})
|
|
return h.client
|
|
}
|
|
|
|
func (h *HttpClient) HttpRequest(ctx context.Context, method, url string, body interface{}, headers map[string]string) (*http.Response, error) {
|
|
payload, err := json.Marshal(body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
req, err := http.NewRequestWithContext(ctx, method, url, bytes.NewBuffer(payload))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
for headerTitle, headerValue := range headers {
|
|
req.Header.Set(headerTitle, headerValue)
|
|
}
|
|
|
|
resp, err := h.getClient().Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
return &http.Response{
|
|
Status: "200 ok",
|
|
StatusCode: 200,
|
|
Body: resp.Body,
|
|
}, nil
|
|
}
|