File: projects_client.go

package info (click to toggle)
golang-github-denverdino-aliyungo 0.0~git20180921.13fa8aa-4
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 1,824 kB
  • sloc: xml: 1,359; makefile: 3
file content (164 lines) | stat: -rw-r--r-- 3,608 bytes parent folder | download | duplicates (3)
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
package cs

import (
	"bytes"
	"crypto/tls"
	"crypto/x509"
	"encoding/json"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"time"

	"strings"

	"github.com/denverdino/aliyungo/common"
	"github.com/denverdino/aliyungo/util"
)

type ProjectClient struct {
	clusterId  string
	endpoint   string
	debug      bool
	userAgent  string
	httpClient *http.Client
}

func NewProjectClient(clusterId, endpoint string, clusterCerts ClusterCerts) (client *ProjectClient, err error) {

	certs, err := tls.X509KeyPair([]byte(clusterCerts.Cert), []byte(clusterCerts.Key))

	if err != nil {
		return
	}

	caCertPool := x509.NewCertPool()
	caCertPool.AppendCertsFromPEM([]byte(clusterCerts.CA))

	httpClient := &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{
				InsecureSkipVerify: true,
				Certificates:       []tls.Certificate{certs},
				ClientCAs:          caCertPool,
				ClientAuth:         tls.RequireAndVerifyClientCert,
			},
		},
	}

	client = &ProjectClient{
		clusterId:  clusterId,
		endpoint:   endpoint,
		httpClient: httpClient,
	}

	return
}

// SetDebug sets debug mode to log the request/response message
func (client *ProjectClient) SetDebug(debug bool) {
	client.debug = debug
}

// SetUserAgent sets user agent to log the request/response message
func (client *ProjectClient) SetUserAgent(userAgent string) {
	client.userAgent = userAgent
}

func (client *ProjectClient) ClusterId() string {
	return client.clusterId
}

func (client *ProjectClient) Endpoint() string {
	return client.endpoint
}

func (client *ProjectClient) Invoke(method string, path string, query url.Values, args interface{}, response interface{}) error {
	var reqBody []byte
	var err error
	var contentType string

	if args != nil {
		reqBody, err = json.Marshal(args)
		if err != nil {
			return err
		}
		contentType = "application/json"
	}

	requestURL := client.endpoint + path
	if query != nil && len(query) > 0 {
		requestURL = requestURL + "?" + util.Encode(query)
	}
	var bodyReader io.Reader
	if reqBody != nil {
		bodyReader = bytes.NewReader(reqBody)
	}

	httpReq, err := http.NewRequest(method, requestURL, bodyReader)
	if err != nil {
		return common.GetClientError(err)
	}

	httpReq.Header.Set("Date", util.GetGMTime())
	httpReq.Header.Set("Accept", "application/json")

	if contentType != "" {
		httpReq.Header.Set("Content-Type", contentType)
	}

	if client.userAgent != "" {
		httpReq.Header.Set("User-Agent", client.userAgent)
	}

	t0 := time.Now()
	httpResp, err := client.httpClient.Do(httpReq)
	t1 := time.Now()
	if err != nil {
		return common.GetClientError(err)
	}
	statusCode := httpResp.StatusCode

	if client.debug {
		log.Printf("Invoke %s %s %d (%v)", method, requestURL, statusCode, t1.Sub(t0))
	}

	defer httpResp.Body.Close()
	body, err := ioutil.ReadAll(httpResp.Body)

	if err != nil {
		return common.GetClientError(err)
	}

	if client.debug {
		var prettyJSON bytes.Buffer
		err = json.Indent(&prettyJSON, body, "", "    ")
		log.Println(string(prettyJSON.Bytes()))
	}

	if statusCode >= 400 && statusCode <= 599 {
		errorResponse := common.ErrorResponse{}
		err = json.Unmarshal(body, &errorResponse)
		ecsError := &common.Error{
			ErrorResponse: errorResponse,
			StatusCode:    statusCode,
		}

		// Project error is not standard ErrorResponse and its body only contains error message
		if len(strings.TrimSpace(ecsError.Message)) <= 0 {
			ecsError.Message = strings.Trim(string(body[:]), "\n")
		}
		return ecsError
	}

	if response != nil {
		err = json.Unmarshal(body, response)
		if err != nil {
			return common.GetClientError(err)
		}
	}

	return nil
}