GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#6)
by Victor Hugo
01:32
created

mollie.newResponse   A

Complexity

Conditions 2

Size

Total Lines 8
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 7
dl 0
loc 8
ccs 6
cts 6
cp 1
crap 2
rs 10
c 0
b 0
f 0
nop 1
1
package mollie
2
3
import (
4
	"bytes"
5
	"encoding/json"
6
	"errors"
7
	"fmt"
8
	"io"
9
	"io/ioutil"
10
	"net/http"
11
	"net/url"
12
	"os"
13
	"strings"
14
)
15
16
// Mollie  constants holding values to initialize the client and create requests.
17
const (
18
	BaseURL            string = "https://api.mollie.com/"
19
	AuthHeader         string = "Authorization"
20
	TokenType          string = "Bearer"
21
	APITokenEnv        string = "MOLLIE_API_TOKEN"
22
	OrgTokenEnv        string = "MOLLIE_ORG_TOKEN"
23
	RequestContentType string = "application/json"
24
)
25
26
var (
27
	errEmptyAPIKey = errors.New("you must provide a non-empty API key")
28
	errBadBaseURL  = errors.New("malformed base url, it must contain a trailing slash")
29
)
30
31
// Client manages communication with Mollie's API.
32
type Client struct {
33
	BaseURL        *url.URL
34
	authentication string
35
	client         *http.Client
36
	common         service // Reuse a single struct instead of allocating one for each service on the heap.
37
	config         *Config
38
	// Services
39
	Payments *PaymentsService
40
}
41
42
type service struct {
43
	client *Client
44
}
45
46
// WithAuthenticationValue offers a convenient setter for any of the valid authentication
47
// tokens provided by Mollie.
48
//
49
// Ideally your API key will be provided from and environment variable or
50
// a secret management engine.
51
// This should only be used when environment variables are "impossible" to be used.
52
func (c *Client) WithAuthenticationValue(k string) error {
53 1
	if k == "" {
54 1
		return errEmptyAPIKey
55
	}
56
57 1
	c.authentication = strings.TrimSpace(k)
58
59 1
	return nil
60
}
61
62
// NewAPIRequest is a wrapper around the http.NewRequest function.
63
//
64
// It will setup the authentication headers/parameters according to the client config.
65
func (c *Client) NewAPIRequest(method string, uri string, body interface{}) (req *http.Request, err error) {
66 1
	if !strings.HasSuffix(c.BaseURL.Path, "/") {
67 1
		return nil, errBadBaseURL
68
	}
69
70 1
	u, err := c.BaseURL.Parse(uri)
71 1
	if err != nil {
72 1
		return nil, err
73
	}
74
75 1
	if c.config.testing == true {
76 1
		u.Query().Add("testmode", "true")
77
	}
78
79 1
	var buf io.ReadWriter
80 1
	if body != nil {
81 1
		buf = new(bytes.Buffer)
82 1
		enc := json.NewEncoder(buf)
83 1
		enc.SetEscapeHTML(false)
84 1
		err := enc.Encode(body)
85 1
		if err != nil {
86 1
			return nil, err
87
		}
88
	}
89
90 1
	req, err = http.NewRequest(method, u.String(), buf)
91 1
	if err != nil {
92 1
		return nil, err
93
	}
94
95 1
	req.Header.Add(AuthHeader, strings.Join([]string{TokenType, c.authentication}, " "))
96
97 1
	if body != nil {
98 1
		req.Header.Set("Content-Type", RequestContentType)
99
	}
100 1
	req.Header.Set("Accept", RequestContentType)
101
102 1
	return
103
}
104
105
// Do sends an API request and returns the API response or returned as an
106
// error if an API error has occurred.
107
func (c *Client) Do(req *http.Request) (*Response, error) {
108 1
	resp, err := c.client.Do(req)
109 1
	if err != nil {
110
		return nil, err
111
	}
112 1
	defer resp.Body.Close()
113 1
	response := newResponse(resp)
114 1
	err = CheckResponse(resp)
115 1
	if err != nil {
116 1
		return nil, err
117
	}
118
119 1
	return response, nil
120
}
121
122
// NewClient returns a new Mollie HTTP API client.
123
// You can pass a previously build http client, if none is provided then
124
// http.DefaultClient will be used.
125
//
126
// NewClient will lookup the environment for values to assign to the
127
// API token (`MOLLIE_API_TOKEN`) and the Organization token (`MOLLIE_ORG_TOKEN`)
128
// according to the provided Config object.
129
//
130
// You can also set the token values programmatically by using the Client
131
// WithAPIKey and WithOrganizationKey functions.
132
func NewClient(baseClient *http.Client, c *Config) (mollie *Client, err error) {
133 1
	if baseClient == nil {
134 1
		baseClient = http.DefaultClient
135
	}
136
137 1
	u, _ := url.Parse(BaseURL)
138
139 1
	mollie = &Client{
140
		BaseURL: u,
141
		client:  baseClient,
142
		config:  c,
143
	}
144
145 1
	mollie.common.client = mollie
146
147
	// services for resources
148 1
	mollie.Payments = (*PaymentsService)(&mollie.common)
149
150
	// Parse authorization from environment
151 1
	if tkn, ok := os.LookupEnv(APITokenEnv); ok {
152 1
		mollie.authentication = tkn
153
	}
154 1
	return
155
}
156
157
/*
158
Error reports details on a failed API request.
159
The success or failure of each HTTP request is shown in the status field of the HTTP response header,
160
which contains standard HTTP status codes:
161
- a 2xx code for success
162
- a 4xx or 5xx code for failure
163
*/
164
type Error struct {
165
	Code     int            `json:"code"`
166
	Message  string         `json:"message"`
167
	Response *http.Response `json:"response"` // the full response that produced the error
168
}
169
170
// Error functions implement the Error interface on the zuora.Error struct.
171
func (e *Error) Error() string {
172 1
	return fmt.Sprintf("response failed with status %v", e.Message)
173
}
174
175
/*
176
Constructor for Error
177
*/
178
func newError(r *http.Response) *Error {
179 1
	var e Error
180 1
	e.Response = r
181 1
	e.Code = r.StatusCode
182 1
	e.Message = r.Status
183 1
	return &e
184
}
185
186
// Response is a Mollie API response. This wraps the standard http.Response
187
// returned from Mollie and provides convenient access to things like
188
// pagination links.
189
type Response struct {
190
	*http.Response
191
	content []byte
192
}
193
194
func newResponse(r *http.Response) *Response {
195 1
	var res Response
196 1
	if c, err := ioutil.ReadAll(r.Body); err == nil {
197 1
		res.content = c
198
	}
199 1
	json.NewDecoder(r.Body).Decode(&res)
200 1
	res.Response = r
201 1
	return &res
202
}
203
204
// CheckResponse checks the API response for errors, and returns them if
205
// present. A response is considered an error if it has a status code outside
206
// the 200 range.
207
// API error responses are expected to have either no response
208
// body, or a JSON response body.
209
func CheckResponse(r *http.Response) error {
210 1
	if r.StatusCode >= http.StatusMultipleChoices {
211 1
		return newError(r)
212
	}
213 1
	return nil
214
}
215