-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient.go
More file actions
277 lines (227 loc) · 5.99 KB
/
client.go
File metadata and controls
277 lines (227 loc) · 5.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
package cvr
// Official client for https://cvr.dev.
// For more information, see https://docs.cvr.dev/.
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/micvbang/go-helpy/inty"
)
const (
APIBaseAddress = "https://api.cvr.dev"
HTTPAuthorizationHeader = "Authorization"
)
// Client provides functionality to request data from cvr.dev.
type Client struct {
client *http.Client
apiBaseAddress string
}
// NewClient returns a client sending requests to the cvr.dev servers.
func NewClient(apiKey string) *Client {
c := &http.Client{Transport: newAuthTransport(apiKey, http.DefaultTransport)}
return &Client{
client: c,
apiBaseAddress: APIBaseAddress,
}
}
// NewClientBaseAddress returns a Client sending requests to the given
// apiBaseAddress.
func NewClientBaseAddress(apiKey string, apiBaseAddress string) *Client {
c := &http.Client{Transport: newAuthTransport(apiKey, http.DefaultTransport)}
return &Client{
client: c,
apiBaseAddress: apiBaseAddress,
}
}
func (c *Client) httpGET(endpoint string) (*http.Response, error) {
req, err := http.NewRequest("GET", endpoint, nil)
if err != nil {
return nil, err
}
return c.client.Do(req)
}
func (c *Client) statusCodeToError(r *http.Response) error {
switch {
case r.StatusCode == http.StatusUnauthorized:
return ErrUnauthorized
case r.StatusCode == http.StatusNotFound:
return ErrNotFound
case r.StatusCode > http.StatusOK:
bs, _ := ioutil.ReadAll(r.Body)
return ErrServerError{
Message: string(bs),
}
default:
return nil
}
}
func (c *Client) buildURL(endpoint string, params map[string]string) (string, error) {
u, err := url.Parse(fmt.Sprintf("%s/api/%s", c.apiBaseAddress, endpoint))
if err != nil {
return "", err
}
urlValues := url.Values{}
for key, value := range params {
urlValues.Add(key, value)
}
return fmt.Sprintf("%s?%s", u.String(), urlValues.Encode()), nil
}
var (
ErrUnauthorized = errors.New("unauthorized")
ErrNotFound = errors.New("not found")
)
type ErrServerError struct {
Message string
}
func (e ErrServerError) Error() string {
return fmt.Sprintf("server error: %s", e.Message)
}
// TestAPIKey returns nil if Client successfully authenticated with the
// server.
func (c *Client) TestAPIKey() error {
endpoint, err := c.buildURL("test/apikey", nil)
if err != nil {
return err
}
r, err := c.httpGET(endpoint)
if err != nil {
return err
}
defer r.Body.Close()
err = c.statusCodeToError(r)
if err != nil {
return err
}
return nil
}
// CVRVirksomhederByCVRNumre returns a list of Virksomheder with the given
// CVR numre. At most 10 virksomheder can be requested at once.
// NOTE: this data originates directly from CVR and is not validated in any way.
func (c *Client) CVRVirksomhederByCVRNumre(cvrNumre ...int) ([]Virksomhed, error) {
cvrNumre = cvrNumre[0:inty.Min(9, len(cvrNumre))]
cvrNumreStr := make([]string, len(cvrNumre))
for i, cvrNummer := range cvrNumre {
cvrNumreStr[i] = strconv.Itoa(cvrNummer)
}
endpoint, err := c.buildURL("cvr/virksomhed", map[string]string{
"cvr_nummer": strings.Join(cvrNumreStr, ","),
})
if err != nil {
return nil, nil
}
r, err := c.httpGET(endpoint)
if err != nil {
return nil, err
}
defer r.Body.Close()
err = c.statusCodeToError(r)
if err != nil {
return nil, err
}
v := []Virksomhed{}
err = json.NewDecoder(r.Body).Decode(&v)
if err != nil {
return nil, err
}
return v, nil
}
// CVRVirksomhederByNavn returns a list of Virksomheder with names similar to
// the given navn. At most 25 virksomheder are returned.
// NOTE: this data originates directly from CVR and is not validated in any way.
func (c *Client) CVRVirksomhederByNavn(navn string) ([]Virksomhed, error) {
endpoint, err := c.buildURL("cvr/virksomhed", map[string]string{
"navn": navn,
})
if err != nil {
return nil, nil
}
r, err := c.httpGET(endpoint)
if err != nil {
return nil, err
}
defer r.Body.Close()
err = c.statusCodeToError(r)
if err != nil {
return nil, err
}
vs := []Virksomhed{}
err = json.NewDecoder(r.Body).Decode(&vs)
if err != nil {
return nil, err
}
return vs, nil
}
// CVRProduktionsenhederByPNumre returns a list of Produktionsenheder with the
// given CVR numre. At most 10 produktionsenheder can be requested at once.
// NOTE: this data originates directly from CVR and is not validated in any way.
func (c *Client) CVRProduktionsenhederByPNumre(pNumre ...int) ([]Produktionsenhed, error) {
pNumre = pNumre[0:inty.Min(9, len(pNumre))]
pNumreStr := make([]string, len(pNumre))
for i, cvrNummer := range pNumre {
pNumreStr[i] = strconv.Itoa(cvrNummer)
}
endpoint, err := c.buildURL("cvr/produktionsenhed", map[string]string{
"p_nummer": strings.Join(pNumreStr, ","),
})
if err != nil {
return nil, nil
}
r, err := c.httpGET(endpoint)
if err != nil {
return nil, err
}
defer r.Body.Close()
err = c.statusCodeToError(r)
if err != nil {
return nil, err
}
v := []Produktionsenhed{}
err = json.NewDecoder(r.Body).Decode(&v)
if err != nil {
return nil, err
}
return v, nil
}
func (c *Client) CVRProduktionsenhederByAdresse(adresse string) ([]Produktionsenhed, error) {
endpoint, err := c.buildURL("cvr/produktionsenhed", map[string]string{
"adresse": adresse,
})
if err != nil {
return nil, nil
}
r, err := c.httpGET(endpoint)
if err != nil {
return nil, err
}
defer r.Body.Close()
err = c.statusCodeToError(r)
if err != nil {
return nil, err
}
v := []Produktionsenhed{}
err = json.NewDecoder(r.Body).Decode(&v)
if err != nil {
return nil, err
}
return v, nil
}
// authTransport is used to add Authentication headers to HTTP requests
type authTransport struct {
apiKey string
orig http.RoundTripper
}
func newAuthTransport(apiKey string, orig http.RoundTripper) http.RoundTripper {
return &authTransport{
apiKey: apiKey,
orig: orig,
}
}
func (at *authTransport) RoundTrip(req *http.Request) (*http.Response, error) {
req.Header.Add("Authorization", at.apiKey)
return at.orig.RoundTrip(req)
}