Test Failed
Push — main ( 35e706...ca941c )
by Acho
01:54
created

mtnmomo.*Client.addBasicAuth   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
package mtnmomo
2
3
import (
4
	"bytes"
5
	"context"
6
	"encoding/json"
7
	"fmt"
8
	"io"
9
	"io/ioutil"
10
	"net/http"
11
)
12
13
const (
14
	subscriptionKeyHeaderKey = "Ocp-Apim-Subscription-Key"
15
)
16
17
type service struct {
18
	client *Client
19
}
20
21
// Client is the campay API client.
22
// Do not instantiate this client with Client{}. Use the New method instead.
23
type Client struct {
24
	httpClient               *http.Client
25
	common                   service
26
	baseURL                  string
27
	subscriptionKey          string
28
	collectionToken          string
29
	collectionTokenExpiresAt int64
30
	apiUser                  string
31
	apiKey                   string
32
33
	APIUser    *apiUserService
34
	Collection *collectionService
35
}
36
37
// New creates and returns a new campay.Client from a slice of campay.ClientOption.
38
func New(options ...Option) *Client {
39
	config := defaultClientConfig()
40
41
	for _, option := range options {
42
		option.apply(config)
43
	}
44
45
	client := &Client{
46
		httpClient:      config.httpClient,
47
		subscriptionKey: config.subscriptionKey,
48
		baseURL:         config.baseURL,
49
		apiKey:          config.apiKey,
50
		apiUser:         config.apiUser,
51
	}
52
53
	client.common.client = client
54
	client.APIUser = (*apiUserService)(&client.common)
55
	client.Collection = (*collectionService)(&client.common)
56
	return client
57
}
58
59
// newRequest creates an API request. A relative URL can be provided in uri,
60
// in which case it is resolved relative to the BaseURL of the Client.
61
// URI's should always be specified without a preceding slash.
62
func (client *Client) newRequest(ctx context.Context, method, uri string, body interface{}) (*http.Request, error) {
63
	var buf io.ReadWriter
64
	if body != nil {
65
		buf = &bytes.Buffer{}
66
		enc := json.NewEncoder(buf)
67
		enc.SetEscapeHTML(false)
68
		err := enc.Encode(body)
69
		if err != nil {
70
			return nil, err
71
		}
72
	}
73
74
	req, err := http.NewRequestWithContext(ctx, method, client.baseURL+uri, buf)
75
	if err != nil {
76
		return nil, err
77
	}
78
79
	req.Header.Set("Content-Type", "application/json")
80
	req.Header.Set("Accept", "application/json")
81
	req.Header.Set(subscriptionKeyHeaderKey, client.subscriptionKey)
82
83
	return req, nil
84
}
85
86
/*
87
// addURLParams adds urls parameters to an *http.Request
88
func (client *Client) addURLParams(request *http.Request, params map[string]string) *http.Request {
89
	q := request.URL.Query()
90
	for key, value := range params {
91
		q.Add(key, value)
92
	}
93
	request.URL.RawQuery = q.Encode()
94
	return request
95
}
96
*/
97
func (client *Client) addBasicAuth(request *http.Request) *http.Request {
98
	request.SetBasicAuth(client.apiUser, client.apiKey)
99
	return request
100
}
101
102
// do carries out an HTTP request and returns a Response
103
func (client *Client) do(req *http.Request) (*Response, error) {
104
	httpResponse, err := client.httpClient.Do(req)
105
	if err != nil {
106
		return nil, err
107
	}
108
109
	defer func() { _ = httpResponse.Body.Close() }()
110
111
	resp, err := client.newResponse(httpResponse)
112
	if err != nil {
113
		return resp, err
114
	}
115
116
	_, err = io.Copy(ioutil.Discard, httpResponse.Body)
117
	if err != nil {
118
		return resp, err
119
	}
120
121
	return resp, nil
122
}
123
124
// newResponse converts an *http.Response to *Response
125
func (client *Client) newResponse(httpResponse *http.Response) (*Response, error) {
126
	if httpResponse == nil {
127
		return nil, fmt.Errorf("%T cannot be nil", httpResponse)
128
	}
129
130
	resp := new(Response)
131
	resp.HTTPResponse = httpResponse
132
133
	buf, err := ioutil.ReadAll(resp.HTTPResponse.Body)
134
	if err != nil {
135
		return nil, err
136
	}
137
	resp.Body = &buf
138
139
	return resp, resp.Error()
140
}
141