-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgocnpj.go
74 lines (59 loc) · 1.15 KB
/
gocnpj.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
package gocnpj
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"net/url"
"path"
"regexp"
)
type service struct {
BaseURL url.URL
}
type Service interface {
Search(cnpj string) (*Company, error)
}
func NewService() Service {
return &service{
BaseURL: url.URL{
Scheme: "https",
Host: "www.receitaws.com.br",
Path: "v1/",
},
}
}
func (s *service) Search(cnpj string) (*Company, error) {
exp := regexp.MustCompile(`[^0-9]`)
cnpj = exp.ReplaceAllString(cnpj, "")
if len(cnpj) != 14 {
return nil, errors.New("cnpj must be 14 characters")
}
url, err := s.BaseURL.Parse(path.Join("cnpj", cnpj))
if err != nil {
return nil, err
}
resp, err := http.Get(url.String())
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var companyError *CompanyError
err = json.Unmarshal(body, &companyError)
if err != nil {
return nil, err
}
if companyError.Status != "OK" {
return nil, errors.New(companyError.Message)
}
var company *Company
err = json.Unmarshal(body, &company)
if err != nil {
return nil, err
}
return company, err
}