You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

436 lines
11 KiB

4 years ago
6 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
  1. package cos
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/base64"
  6. "encoding/xml"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "net/http"
  11. "net/url"
  12. "reflect"
  13. "strings"
  14. "text/template"
  15. "strconv"
  16. "github.com/google/go-querystring/query"
  17. "github.com/mozillazg/go-httpheader"
  18. )
  19. const (
  20. // Version current go sdk version
  21. Version = "0.7.25"
  22. userAgent = "cos-go-sdk-v5/" + Version
  23. contentTypeXML = "application/xml"
  24. defaultServiceBaseURL = "http://service.cos.myqcloud.com"
  25. )
  26. var bucketURLTemplate = template.Must(
  27. template.New("bucketURLFormat").Parse(
  28. "{{.Schema}}://{{.BucketName}}.cos.{{.Region}}.myqcloud.com",
  29. ),
  30. )
  31. // BaseURL 访问各 API 所需的基础 URL
  32. type BaseURL struct {
  33. // 访问 bucket, object 相关 API 的基础 URL(不包含 path 部分): http://example.com
  34. BucketURL *url.URL
  35. // 访问 service API 的基础 URL(不包含 path 部分): http://example.com
  36. ServiceURL *url.URL
  37. // 访问 job API 的基础 URL (不包含 path 部分): http://example.com
  38. BatchURL *url.URL
  39. // 访问 CI 的基础 URL
  40. CIURL *url.URL
  41. }
  42. // NewBucketURL 生成 BaseURL 所需的 BucketURL
  43. //
  44. // bucketName: bucket名称, bucket的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
  45. // Region: 区域代码: ap-beijing-1,ap-beijing,ap-shanghai,ap-guangzhou...
  46. // secure: 是否使用 https
  47. func NewBucketURL(bucketName, region string, secure bool) *url.URL {
  48. schema := "https"
  49. if !secure {
  50. schema = "http"
  51. }
  52. w := bytes.NewBuffer(nil)
  53. bucketURLTemplate.Execute(w, struct {
  54. Schema string
  55. BucketName string
  56. Region string
  57. }{
  58. schema, bucketName, region,
  59. })
  60. u, _ := url.Parse(w.String())
  61. return u
  62. }
  63. type Config struct {
  64. EnableCRC bool
  65. RequestBodyClose bool
  66. }
  67. // Client is a client manages communication with the COS API.
  68. type Client struct {
  69. client *http.Client
  70. Host string
  71. UserAgent string
  72. BaseURL *BaseURL
  73. common service
  74. Service *ServiceService
  75. Bucket *BucketService
  76. Object *ObjectService
  77. Batch *BatchService
  78. CI *CIService
  79. Conf *Config
  80. }
  81. type service struct {
  82. client *Client
  83. }
  84. // NewClient returns a new COS API client.
  85. func NewClient(uri *BaseURL, httpClient *http.Client) *Client {
  86. if httpClient == nil {
  87. httpClient = &http.Client{}
  88. }
  89. baseURL := &BaseURL{}
  90. if uri != nil {
  91. baseURL.BucketURL = uri.BucketURL
  92. baseURL.ServiceURL = uri.ServiceURL
  93. baseURL.BatchURL = uri.BatchURL
  94. baseURL.CIURL = uri.CIURL
  95. }
  96. if baseURL.ServiceURL == nil {
  97. baseURL.ServiceURL, _ = url.Parse(defaultServiceBaseURL)
  98. }
  99. c := &Client{
  100. client: httpClient,
  101. UserAgent: userAgent,
  102. BaseURL: baseURL,
  103. Conf: &Config{
  104. EnableCRC: true,
  105. RequestBodyClose: false,
  106. },
  107. }
  108. c.common.client = c
  109. c.Service = (*ServiceService)(&c.common)
  110. c.Bucket = (*BucketService)(&c.common)
  111. c.Object = (*ObjectService)(&c.common)
  112. c.Batch = (*BatchService)(&c.common)
  113. c.CI = (*CIService)(&c.common)
  114. return c
  115. }
  116. func (c *Client) newRequest(ctx context.Context, baseURL *url.URL, uri, method string, body interface{}, optQuery interface{}, optHeader interface{}) (req *http.Request, err error) {
  117. uri, err = addURLOptions(uri, optQuery)
  118. if err != nil {
  119. return
  120. }
  121. u, _ := url.Parse(uri)
  122. urlStr := baseURL.ResolveReference(u).String()
  123. var reader io.Reader
  124. contentType := ""
  125. contentMD5 := ""
  126. if body != nil {
  127. // 上传文件
  128. if r, ok := body.(io.Reader); ok {
  129. reader = r
  130. } else {
  131. b, err := xml.Marshal(body)
  132. if err != nil {
  133. return nil, err
  134. }
  135. contentType = contentTypeXML
  136. reader = bytes.NewReader(b)
  137. contentMD5 = base64.StdEncoding.EncodeToString(calMD5Digest(b))
  138. }
  139. }
  140. req, err = http.NewRequest(method, urlStr, reader)
  141. if err != nil {
  142. return
  143. }
  144. req.Header, err = addHeaderOptions(req.Header, optHeader)
  145. if err != nil {
  146. return
  147. }
  148. if v := req.Header.Get("Content-Length"); req.ContentLength == 0 && v != "" && v != "0" {
  149. req.ContentLength, _ = strconv.ParseInt(v, 10, 64)
  150. }
  151. if contentMD5 != "" {
  152. req.Header["Content-MD5"] = []string{contentMD5}
  153. }
  154. if c.UserAgent != "" {
  155. req.Header.Set("User-Agent", c.UserAgent)
  156. }
  157. if req.Header.Get("Content-Type") == "" && contentType != "" {
  158. req.Header.Set("Content-Type", contentType)
  159. }
  160. if c.Host != "" {
  161. req.Host = c.Host
  162. }
  163. if c.Conf.RequestBodyClose {
  164. req.Close = true
  165. }
  166. return
  167. }
  168. func (c *Client) doAPI(ctx context.Context, req *http.Request, result interface{}, closeBody bool) (*Response, error) {
  169. req = req.WithContext(ctx)
  170. resp, err := c.client.Do(req)
  171. if err != nil {
  172. // If we got an error, and the context has been canceled,
  173. // the context's error is probably more useful.
  174. select {
  175. case <-ctx.Done():
  176. return nil, ctx.Err()
  177. default:
  178. }
  179. return nil, err
  180. }
  181. defer func() {
  182. if closeBody {
  183. // Close the body to let the Transport reuse the connection
  184. io.Copy(ioutil.Discard, resp.Body)
  185. resp.Body.Close()
  186. }
  187. }()
  188. response := newResponse(resp)
  189. err = checkResponse(resp)
  190. if err != nil {
  191. // even though there was an error, we still return the response
  192. // in case the caller wants to inspect it further
  193. return response, err
  194. }
  195. // need CRC64 verification
  196. if reader, ok := req.Body.(*teeReader); ok {
  197. if c.Conf.EnableCRC && reader.writer != nil {
  198. localcrc := reader.Crc64()
  199. scoscrc := response.Header.Get("x-cos-hash-crc64ecma")
  200. icoscrc, _ := strconv.ParseUint(scoscrc, 10, 64)
  201. if icoscrc != localcrc {
  202. return response, fmt.Errorf("verification failed, want:%v, return:%v", localcrc, icoscrc)
  203. }
  204. }
  205. }
  206. if result != nil {
  207. if w, ok := result.(io.Writer); ok {
  208. io.Copy(w, resp.Body)
  209. } else {
  210. err = xml.NewDecoder(resp.Body).Decode(result)
  211. if err == io.EOF {
  212. err = nil // ignore EOF errors caused by empty response body
  213. }
  214. }
  215. }
  216. return response, err
  217. }
  218. type sendOptions struct {
  219. // 基础 URL
  220. baseURL *url.URL
  221. // URL 中除基础 URL 外的剩余部分
  222. uri string
  223. // 请求方法
  224. method string
  225. body interface{}
  226. // url 查询参数
  227. optQuery interface{}
  228. // http header 参数
  229. optHeader interface{}
  230. // 用 result 反序列化 resp.Body
  231. result interface{}
  232. // 是否禁用自动调用 resp.Body.Close()
  233. // 自动调用 Close() 是为了能够重用连接
  234. disableCloseBody bool
  235. }
  236. func (c *Client) send(ctx context.Context, opt *sendOptions) (resp *Response, err error) {
  237. req, err := c.newRequest(ctx, opt.baseURL, opt.uri, opt.method, opt.body, opt.optQuery, opt.optHeader)
  238. if err != nil {
  239. return
  240. }
  241. resp, err = c.doAPI(ctx, req, opt.result, !opt.disableCloseBody)
  242. return
  243. }
  244. // addURLOptions adds the parameters in opt as URL query parameters to s. opt
  245. // must be a struct whose fields may contain "url" tags.
  246. func addURLOptions(s string, opt interface{}) (string, error) {
  247. v := reflect.ValueOf(opt)
  248. if v.Kind() == reflect.Ptr && v.IsNil() {
  249. return s, nil
  250. }
  251. u, err := url.Parse(s)
  252. if err != nil {
  253. return s, err
  254. }
  255. qs, err := query.Values(opt)
  256. if err != nil {
  257. return s, err
  258. }
  259. // 保留原有的参数,并且放在前面。因为 cos 的 url 路由是以第一个参数作为路由的
  260. // e.g. /?uploads
  261. q := u.RawQuery
  262. rq := qs.Encode()
  263. if q != "" {
  264. if rq != "" {
  265. u.RawQuery = fmt.Sprintf("%s&%s", q, qs.Encode())
  266. }
  267. } else {
  268. u.RawQuery = rq
  269. }
  270. return u.String(), nil
  271. }
  272. // addHeaderOptions adds the parameters in opt as Header fields to req. opt
  273. // must be a struct whose fields may contain "header" tags.
  274. func addHeaderOptions(header http.Header, opt interface{}) (http.Header, error) {
  275. v := reflect.ValueOf(opt)
  276. if v.Kind() == reflect.Ptr && v.IsNil() {
  277. return header, nil
  278. }
  279. h, err := httpheader.Header(opt)
  280. if err != nil {
  281. return nil, err
  282. }
  283. for key, values := range h {
  284. for _, value := range values {
  285. header.Add(key, value)
  286. }
  287. }
  288. return header, nil
  289. }
  290. // Owner defines Bucket/Object's owner
  291. type Owner struct {
  292. UIN string `xml:"uin,omitempty"`
  293. ID string `xml:",omitempty"`
  294. DisplayName string `xml:",omitempty"`
  295. }
  296. // Initiator same to the Owner struct
  297. type Initiator Owner
  298. // Response API 响应
  299. type Response struct {
  300. *http.Response
  301. }
  302. func newResponse(resp *http.Response) *Response {
  303. return &Response{
  304. Response: resp,
  305. }
  306. }
  307. // ACLHeaderOptions is the option of ACLHeader
  308. type ACLHeaderOptions struct {
  309. XCosACL string `header:"x-cos-acl,omitempty" url:"-" xml:"-"`
  310. XCosGrantRead string `header:"x-cos-grant-read,omitempty" url:"-" xml:"-"`
  311. XCosGrantWrite string `header:"x-cos-grant-write,omitempty" url:"-" xml:"-"`
  312. XCosGrantFullControl string `header:"x-cos-grant-full-control,omitempty" url:"-" xml:"-"`
  313. XCosGrantReadACP string `header:"x-cos-grant-read-acp,omitempty" url:"-" xml:"-"`
  314. XCosGrantWriteACP string `header:"x-cos-grant-write-acp,omitempty" url:"-" xml:"-"`
  315. }
  316. // ACLGrantee is the param of ACLGrant
  317. type ACLGrantee struct {
  318. Type string `xml:"type,attr"`
  319. UIN string `xml:"uin,omitempty"`
  320. URI string `xml:"URI,omitempty"`
  321. ID string `xml:",omitempty"`
  322. DisplayName string `xml:",omitempty"`
  323. SubAccount string `xml:"Subaccount,omitempty"`
  324. }
  325. // ACLGrant is the param of ACLXml
  326. type ACLGrant struct {
  327. Grantee *ACLGrantee
  328. Permission string
  329. }
  330. // ACLXml is the ACL body struct
  331. type ACLXml struct {
  332. XMLName xml.Name `xml:"AccessControlPolicy"`
  333. Owner *Owner
  334. AccessControlList []ACLGrant `xml:"AccessControlList>Grant,omitempty"`
  335. }
  336. func decodeACL(resp *Response, res *ACLXml) {
  337. ItemMap := map[string]string{
  338. "ACL": "x-cos-acl",
  339. "READ": "x-cos-grant-read",
  340. "WRITE": "x-cos-grant-write",
  341. "READ_ACP": "x-cos-grant-read-acp",
  342. "WRITE_ACP": "x-cos-grant-write-acp",
  343. "FULL_CONTROL": "x-cos-grant-full-control",
  344. }
  345. publicACL := make(map[string]int)
  346. resACL := make(map[string][]string)
  347. for _, item := range res.AccessControlList {
  348. if item.Grantee == nil {
  349. continue
  350. }
  351. if item.Grantee.ID == "qcs::cam::anyone:anyone" || item.Grantee.URI == "http://cam.qcloud.com/groups/global/AllUsers" {
  352. publicACL[item.Permission] = 1
  353. } else if item.Grantee.ID != res.Owner.ID {
  354. resACL[item.Permission] = append(resACL[item.Permission], "id=\""+item.Grantee.ID+"\"")
  355. }
  356. }
  357. if publicACL["FULL_CONTROL"] == 1 || (publicACL["READ"] == 1 && publicACL["WRITE"] == 1) {
  358. resACL["ACL"] = []string{"public-read-write"}
  359. } else if publicACL["READ"] == 1 {
  360. resACL["ACL"] = []string{"public-read"}
  361. } else {
  362. resACL["ACL"] = []string{"private"}
  363. }
  364. for item, header := range ItemMap {
  365. if len(resp.Header.Get(header)) > 0 || len(resACL[item]) == 0 {
  366. continue
  367. }
  368. resp.Header.Set(header, uniqueGrantID(resACL[item]))
  369. }
  370. }
  371. func uniqueGrantID(grantIDs []string) string {
  372. res := []string{}
  373. filter := make(map[string]int)
  374. for _, id := range grantIDs {
  375. if filter[id] != 0 {
  376. continue
  377. }
  378. filter[id] = 1
  379. res = append(res, id)
  380. }
  381. return strings.Join(res, ",")
  382. }