Debian Codegraph @

cms/apiproxy.go

raw symbols SCIP
1 package cms
2
3 import (
4 "bytes"
5 "log"
6 "time"
7
8 "github.com/denverdino/aliyungo/cms/util"
9 // "fmt"
10 "encoding/json"
11 "errors"
12 "io/ioutil"
13 "net/http"
14 "sort"
15 "strings"
16 )
17
18 const (
19 HEADER_SEPERATER = "\n"
20 ACS_PREFIX = "x-acs"
21 )
22
23 /**
24 * 这个方法是先POP签名,并写入到协议头中
25 * @params
26 * method http方法,GET POST DELETE PUT 等
27 * url 请求的url
28 * header http请求头
29 * querys GET请求参数,则需要设置querys参数
30 * POP签名
31 */
32 func (client *Client) Sign(method string, url string, req *http.Request, querys string) {
33
34 header := req.Header
35
36 var buf bytes.Buffer
37 keys := make([]string, 0, len(header))
38 for k := range header {
39 keys = append(keys, k)
40 }
41 sort.Strings(keys)
42
43 buf.WriteString(method + HEADER_SEPERATER)
44 for _, k := range keys {
45 vs := header[k]
46 // prefix := strings.ToLower(k + ":")
47 prefix := strings.ToLower(k + ":")
48 for _, v := range vs {
49
50 if v != "" {
51 lowerKey := strings.ToLower(k)
52 if strings.Contains(lowerKey, ACS_PREFIX) {
53 buf.WriteString(prefix)
54 buf.WriteString(v)
55 } else {
56 buf.WriteString(v)
57 }
58
59 }
60
61 buf.WriteString("\n")
62 }
63 }
64
65 // 写入url
66 if querys != "" {
67 url = url + "?" + querys
68 }
69 buf.WriteString(url)
70
71 //fmt.Printf("SignString = %s ", buf.String())
72
73 signiture := util.HmacSha1(client.GetAccessSecret(), buf.String())
74
75 header.Add("Authorization", "acs "+client.GetAccessKey()+":"+signiture)
76 }
77
78 /**
79 * 取得上下文请求路径
80 */
81 func GetRequestPath(entity string, project string, id string) string {
82 urlPath := ""
83
84 if entity == "projects" {
85 urlPath = urlPath + "/" + entity
86 } else {
87 urlPath = urlPath + "/projects/" + project + "/" + entity
88 }
89
90 if id != "" {
91 if strings.HasPrefix(id, "?") {
92 urlPath = urlPath + id
93 } else {
94 urlPath = urlPath + "/" + id
95 }
96 }
97
98 return urlPath
99 }
100
101 /**
102 * 去的要请求的url
103 */
104 func (client *Client) GetUrl(entity string, project string, id string) string {
105 var url = client.GetApiUri()
106 url += GetRequestPath(entity, project, id)
107 // var pageStr = "",
108 // filterStr = "";
109 // if (filter) {
110 // for (var kk in filter) {
111 // filterStr += "&" + kk + "=" + filter[kk];
112 // }
113 // }
114 // if (pagination) {
115 // pageStr = "&page=" + (Math.floor(pagination.index / pagination.size) + 1) + "&pageSize=" + pagination.size;
116 // }
117 // if (filterStr || pageStr) {
118 // url += "?resource" + filterStr + pageStr;
119 // }
120 // return url;
121
122 return url
123 }
124
125 /**
126 * 取得公共的头部参数,初始化的时候先将Content
127 */
128 func InitBaseHeader(v *http.Request) {
129
130 v.Header["Accept"] = []string{"application/json"}
131 v.Header.Set("Content-MD5", "")
132 v.Header["Content-Type"] = []string{"application/json"}
133 v.Header["Date"] = []string{util.GetRFCDate()}
134 v.Header["x-acs-signature-method"] = []string{"HMAC-SHA1"}
135 v.Header["x-acs-signature-version"] = []string{"1.0"}
136 v.Header["x-acs-version"] = []string{"2015-08-15"}
137 }
138
139 /**
140 * 对json进行md5 base64
141 */
142 func BodyMd5(jsonstring string) string {
143 return util.Md5Base64_16(jsonstring)
144 }
145
146 /**
147 * 发送http请求,去的响应字符串
148 */
149 func (c *Client) GetResponseJson(method string, requestUrl string, requestPath string, body string) (responseBody string, err error) {
150
151 // fmt.Println("method %s, requestPath: %s", requestUrl, requestPath)
152 reqest, err := http.NewRequest(method, requestUrl, strings.NewReader(body))
153 if err != nil {
154 return responseBody, err
155 }
156
157 InitBaseHeader(reqest)
158
159 // 如果是post请求,并且有post请求内容则加上Content-MD5头
160 if body != "" && method == "POST" {
161 reqest.Header.Set("Content-MD5", BodyMd5(body))
162 }
163
164 if c.securityToken != "" {
165 reqest.Header["x-acs-security-token"] = []string{c.securityToken}
166 }
167
168 c.Sign(method, requestPath, reqest, "")
169
170 if method != "POST" {
171 reqest.Header.Del("Content-MD5")
172
173 }
174 //reqest.Header.Del("Accept-Encoding")
175 reqest.Header.Set("Accept-Encoding", "deflate,sdch")
176
177 log.Printf("RequestUrl = %++v", reqest)
178 client := &http.Client{}
179 t0 := time.Now()
180 response, err := client.Do(reqest)
181 t1 := time.Now()
182 if err != nil {
183 return body, err
184 }
185
186 if c.debug {
187 log.Printf("Invoke %s %s %d (%v)", method, requestUrl, response.StatusCode, t1.Sub(t0))
188 }
189
190 rsBody, err := ioutil.ReadAll(response.Body)
191 if err != nil {
192 return "", err
193 }
194 //如果状态吗是非200则进行返回值的过滤,使得pop返回的错误和程序的错误输出一致
195 if response.StatusCode != 200 {
196 err = errors.New("Response status code faild" + string(rsBody))
197 type ResultError struct {
198 RequestId string `json:"requestId"`
199 HostId string `json:"hostId"`
200 Code string `json:"code"`
201 Message string `json:"Message"`
202 }
203 var rsError ResultError
204 rsBodyString := string(rsBody)
205 _ = json.Unmarshal([]byte(rsBodyString), &rsError)
206
207 newResult := ResultModel{
208 rsError.Code,
209 rsError.Message,
210 false,
211 }
212
213 resultJson, _ := json.Marshal(newResult)
214
215 return string(resultJson), err
216
217 }
218
219 return string(rsBody), err
220 }