-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathares.go
89 lines (74 loc) · 2 KB
/
ares.go
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
package ares
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
)
const EconomicEntityURL = "https://ares.gov.cz/ekonomicke-subjekty-v-be/rest/ekonomicke-subjekty/"
type Client struct {
client *http.Client
}
type EconomicEntity struct {
Name string `json:"obchodniJmeno"`
IC string `json:"ico"`
VatID string `json:"dic"`
Address Address `json:"adresaDorucovaci"`
}
type Address struct {
Line1 string `json:"radekAdresy1"`
Line2 string `json:"radekAdresy2"`
Line3 string `json:"radekAdresy3"`
}
type EntityNotFoundError struct {
IC string
}
func (e EntityNotFoundError) Error() string {
return fmt.Sprintf("economic entity with IC '%s' not found", e.IC)
}
func NewClient(client *http.Client) *Client {
return &Client{client: client}
}
func (c *Client) ByIC(ctx context.Context, id string) (result *EconomicEntity, err error) {
endpoint := EconomicEntityURL + id
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, fmt.Errorf("failed to create HTTP request to ARES: %w", err)
}
resp, err := c.client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to perform HTTP request to ARES: %w", err)
}
defer func() {
if closeErr := resp.Body.Close(); closeErr != nil && err == nil {
err = closeErr
}
}()
switch resp.StatusCode {
case http.StatusOK:
// ok
case http.StatusNotFound:
return nil, fmt.Errorf("economic entity with IC '%s' not found", id)
default:
return nil, EntityNotFoundError{IC: id}
}
result = &EconomicEntity{}
if err := json.NewDecoder(resp.Body).Decode(result); err != nil {
return nil, fmt.Errorf("failed to decode response from ARES: %w", err)
}
return result, nil
}
func (a Address) String() string {
var parts []string
if v := strings.TrimSpace(a.Line1); v != "" {
parts = append(parts, v)
}
if v := strings.TrimSpace(a.Line2); v != "" {
parts = append(parts, v)
}
if v := strings.TrimSpace(a.Line3); v != "" {
parts = append(parts, v)
}
return strings.Join(parts, "\n")
}