ozon-api-client

Форк
0
/
client.go 
132 строки · 2.6 Кб
1
package core
2

3
import (
4
	"bytes"
5
	"context"
6
	"encoding/json"
7
	"io/ioutil"
8
	"net/http"
9
	"net/http/httptest"
10
	"net/url"
11
	"reflect"
12
)
13

14
type HttpClient interface {
15
	Do(req *http.Request) (*http.Response, error)
16
}
17

18
type Client struct {
19
	baseUrl string
20
	Options map[string]string
21

22
	client HttpClient
23
}
24

25
func NewClient(client HttpClient, baseUrl string, opts map[string]string) *Client {
26
	return &Client{
27
		Options: opts,
28
		client:  client,
29
		baseUrl: baseUrl,
30
	}
31
}
32

33
func NewMockClient(handler http.HandlerFunc) *Client {
34
	return &Client{
35
		client: NewMockHttpClient(handler),
36
	}
37
}
38

39
func (c Client) newRequest(ctx context.Context, method string, uri string, body interface{}) (*http.Request, error) {
40
	var err error
41
	var bodyJson []byte
42

43
	// Set default values for empty fields if `default` tag is present
44
	// And body is not nil
45
	if body != nil {
46
		if err := getDefaultValues(reflect.ValueOf(body)); err != nil {
47
			return nil, err
48
		}
49

50
		bodyJson, err = json.Marshal(body)
51
		if err != nil {
52
			return nil, err
53
		}
54
	}
55

56
	uri, err = url.JoinPath(c.baseUrl, uri)
57
	if err != nil {
58
		return nil, err
59
	}
60
	req, err := http.NewRequestWithContext(ctx, method, uri, bytes.NewBuffer(bodyJson))
61
	if err != nil {
62
		return nil, err
63
	}
64

65
	for k, v := range c.Options {
66
		req.Header.Add(k, v)
67
	}
68

69
	return req, nil
70
}
71

72
func (c Client) Request(ctx context.Context, method string, path string, req, resp interface{}, options map[string]string) (*Response, error) {
73
	httpReq, err := c.newRequest(ctx, method, path, req)
74
	if err != nil {
75
		return nil, err
76
	}
77

78
	httpResp, err := c.client.Do(httpReq)
79
	if err != nil {
80
		return nil, err
81
	}
82
	defer httpResp.Body.Close()
83

84
	body, err := ioutil.ReadAll(httpResp.Body)
85
	if err != nil {
86
		return nil, err
87
	}
88

89
	response := &Response{}
90
	response.Data = resp
91
	response.StatusCode = httpResp.StatusCode
92
	if httpResp.StatusCode == http.StatusOK {
93
		err = json.Unmarshal(body, &response.Data)
94
	} else {
95
		err = json.Unmarshal(body, &response)
96
	}
97
	if err != nil {
98
		return nil, err
99
	}
100

101
	return response, nil
102
}
103

104
type MockHttpClient struct {
105
	handler http.HandlerFunc
106
}
107

108
func NewMockHttpClient(handler http.HandlerFunc) *MockHttpClient {
109
	return &MockHttpClient{
110
		handler: handler,
111
	}
112
}
113

114
func (c MockHttpClient) Do(req *http.Request) (*http.Response, error) {
115
	rr := httptest.NewRecorder()
116
	c.handler.ServeHTTP(rr, req)
117

118
	return rr.Result(), nil
119
}
120

121
func NewMockHttpHandler(statusCode int, json string, headers map[string]string) http.HandlerFunc {
122
	return func(w http.ResponseWriter, r *http.Request) {
123
		if len(headers) > 0 {
124
			for key, value := range headers {
125
				w.Header().Add(key, value)
126
			}
127
		}
128

129
		w.WriteHeader(statusCode)
130
		w.Write([]byte(json))
131
	}
132
}
133

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.