-
Notifications
You must be signed in to change notification settings - Fork 0
/
Service.go
106 lines (84 loc) · 2.35 KB
/
Service.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package mailchimp
import (
"encoding/base64"
"fmt"
errortools "github.com/leapforce-libraries/go_errortools"
go_http "github.com/leapforce-libraries/go_http"
"net/http"
)
const (
apiName string = "Mailchimp"
apiUrl string = "https://%s.api.mailchimp.com/3.0"
countDefault int64 = 100
)
type Service struct {
server string
apiKey string
httpService *go_http.Service
errorResponse *ErrorResponse
}
type ServiceConfig struct {
Server string
ApiKey string
}
func NewService(cfg *ServiceConfig) (*Service, *errortools.Error) {
if cfg == nil {
return nil, errortools.ErrorMessage("ServiceConfig must not be a nil pointer")
}
if cfg.Server == "" {
return nil, errortools.ErrorMessage("Server not provided")
}
if cfg.ApiKey == "" {
return nil, errortools.ErrorMessage("ApiKey not provided")
}
var service = Service{
server: cfg.Server,
apiKey: cfg.ApiKey,
}
httpService, e := go_http.NewService(&go_http.ServiceConfig{})
if e != nil {
return nil, e
}
service.httpService = httpService
return &service, nil
}
func (service *Service) httpRequest(requestConfig *go_http.RequestConfig) (*http.Request, *http.Response, *errortools.Error) {
// add authentication
headers := requestConfig.NonDefaultHeaders
if headers == nil {
headers = &http.Header{}
}
headers.Set("Authorization", fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("anystring:%s", service.apiKey)))))
requestConfig.NonDefaultHeaders = headers
// add error model
service.errorResponse = &ErrorResponse{}
requestConfig.ErrorModel = service.errorResponse
request, response, e := service.httpService.HttpRequest(requestConfig)
if e != nil {
if service.errorResponse.Message != "" {
e.SetMessage(service.errorResponse.Message)
}
}
if e != nil {
return request, response, e
}
return request, response, nil
}
func (service *Service) url(path string) string {
return fmt.Sprintf("%s/%s", fmt.Sprintf(apiUrl, service.server), path)
}
func (service *Service) ApiName() string {
return apiName
}
func (service *Service) ApiKey() string {
return service.apiKey
}
func (service *Service) ApiCallCount() int64 {
return service.httpService.RequestCount()
}
func (service *Service) ApiReset() {
service.httpService.ResetRequestCount()
}
func (service *Service) ErrorResponse() *ErrorResponse {
return service.errorResponse
}