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.

347 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. } else {
  119. contentType = contentTypeXML
  120. }
  121. req, err = http.NewRequest(method, urlStr, reader)
  122. if err != nil {
  123. return
  124. }
  125. req.Header, err = addHeaderOptions(req.Header, optHeader)
  126. if err != nil {
  127. return
  128. }
  129. if v := req.Header.Get("Content-Length"); req.ContentLength == 0 && v != "" && v != "0" {
  130. req.ContentLength, _ = strconv.ParseInt(v, 10, 64)
  131. }
  132. if contentMD5 != "" {
  133. req.Header["Content-MD5"] = []string{contentMD5}
  134. }
  135. if c.UserAgent != "" {
  136. req.Header.Set("User-Agent", c.UserAgent)
  137. }
  138. if req.Header.Get("Content-Type") == "" && contentType != "" {
  139. req.Header.Set("Content-Type", contentType)
  140. }
  141. return
  142. }
  143. func (c *Client) doAPI(ctx context.Context, req *http.Request, result interface{}, closeBody bool) (*Response, error) {
  144. req = req.WithContext(ctx)
  145. resp, err := c.client.Do(req)
  146. if err != nil {
  147. // If we got an error, and the context has been canceled,
  148. // the context's error is probably more useful.
  149. select {
  150. case <-ctx.Done():
  151. return nil, ctx.Err()
  152. default:
  153. }
  154. return nil, err
  155. }
  156. defer func() {
  157. if closeBody {
  158. // Close the body to let the Transport reuse the connection
  159. io.Copy(ioutil.Discard, resp.Body)
  160. resp.Body.Close()
  161. }
  162. }()
  163. response := newResponse(resp)
  164. err = checkResponse(resp)
  165. if err != nil {
  166. // even though there was an error, we still return the response
  167. // in case the caller wants to inspect it further
  168. return response, err
  169. }
  170. if result != nil {
  171. if w, ok := result.(io.Writer); ok {
  172. io.Copy(w, resp.Body)
  173. } else {
  174. err = xml.NewDecoder(resp.Body).Decode(result)
  175. if err == io.EOF {
  176. err = nil // ignore EOF errors caused by empty response body
  177. }
  178. }
  179. }
  180. return response, err
  181. }
  182. type sendOptions struct {
  183. // 基础 URL
  184. baseURL *url.URL
  185. // URL 中除基础 URL 外的剩余部分
  186. uri string
  187. // 请求方法
  188. method string
  189. body interface{}
  190. // url 查询参数
  191. optQuery interface{}
  192. // http header 参数
  193. optHeader interface{}
  194. // 用 result 反序列化 resp.Body
  195. result interface{}
  196. // 是否禁用自动调用 resp.Body.Close()
  197. // 自动调用 Close() 是为了能够重用连接
  198. disableCloseBody bool
  199. }
  200. func (c *Client) send(ctx context.Context, opt *sendOptions) (resp *Response, err error) {
  201. req, err := c.newRequest(ctx, opt.baseURL, opt.uri, opt.method, opt.body, opt.optQuery, opt.optHeader)
  202. if err != nil {
  203. return
  204. }
  205. resp, err = c.doAPI(ctx, req, opt.result, !opt.disableCloseBody)
  206. if err != nil {
  207. return
  208. }
  209. return
  210. }
  211. // addURLOptions adds the parameters in opt as URL query parameters to s. opt
  212. // must be a struct whose fields may contain "url" tags.
  213. func addURLOptions(s string, opt interface{}) (string, error) {
  214. v := reflect.ValueOf(opt)
  215. if v.Kind() == reflect.Ptr && v.IsNil() {
  216. return s, nil
  217. }
  218. u, err := url.Parse(s)
  219. if err != nil {
  220. return s, err
  221. }
  222. qs, err := query.Values(opt)
  223. if err != nil {
  224. return s, err
  225. }
  226. // 保留原有的参数,并且放在前面。因为 cos 的 url 路由是以第一个参数作为路由的
  227. // e.g. /?uploads
  228. q := u.RawQuery
  229. rq := qs.Encode()
  230. if q != "" {
  231. if rq != "" {
  232. u.RawQuery = fmt.Sprintf("%s&%s", q, qs.Encode())
  233. }
  234. } else {
  235. u.RawQuery = rq
  236. }
  237. return u.String(), nil
  238. }
  239. // addHeaderOptions adds the parameters in opt as Header fields to req. opt
  240. // must be a struct whose fields may contain "header" tags.
  241. func addHeaderOptions(header http.Header, opt interface{}) (http.Header, error) {
  242. v := reflect.ValueOf(opt)
  243. if v.Kind() == reflect.Ptr && v.IsNil() {
  244. return header, nil
  245. }
  246. h, err := httpheader.Header(opt)
  247. if err != nil {
  248. return nil, err
  249. }
  250. for key, values := range h {
  251. for _, value := range values {
  252. header.Add(key, value)
  253. }
  254. }
  255. return header, nil
  256. }
  257. // Owner defines Bucket/Object's owner
  258. type Owner struct {
  259. UIN string `xml:"uin,omitempty"`
  260. ID string `xml:",omitempty"`
  261. DisplayName string `xml:",omitempty"`
  262. }
  263. // Initiator same to the Owner struct
  264. type Initiator Owner
  265. // Response API 响应
  266. type Response struct {
  267. *http.Response
  268. }
  269. func newResponse(resp *http.Response) *Response {
  270. return &Response{
  271. Response: resp,
  272. }
  273. }
  274. // ACLHeaderOptions is the option of ACLHeader
  275. type ACLHeaderOptions struct {
  276. XCosACL string `header:"x-cos-acl,omitempty" url:"-" xml:"-"`
  277. XCosGrantRead string `header:"x-cos-grant-read,omitempty" url:"-" xml:"-"`
  278. XCosGrantWrite string `header:"x-cos-grant-write,omitempty" url:"-" xml:"-"`
  279. XCosGrantFullControl string `header:"x-cos-grant-full-control,omitempty" url:"-" xml:"-"`
  280. }
  281. // ACLGrantee is the param of ACLGrant
  282. type ACLGrantee struct {
  283. Type string `xml:"type,attr"`
  284. UIN string `xml:"uin,omitempty"`
  285. ID string `xml:",omitempty"`
  286. DisplayName string `xml:",omitempty"`
  287. SubAccount string `xml:"Subaccount,omitempty"`
  288. }
  289. // ACLGrant is the param of ACLXml
  290. type ACLGrant struct {
  291. Grantee *ACLGrantee
  292. Permission string
  293. }
  294. // ACLXml is the ACL body struct
  295. type ACLXml struct {
  296. XMLName xml.Name `xml:"AccessControlPolicy"`
  297. Owner *Owner
  298. AccessControlList []ACLGrant `xml:"AccessControlList>Grant,omitempty"`
  299. }