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.

345 lines
8.0 KiB

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