client.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  1. // Package oss implements functions for access oss service.
  2. // It has two main struct Client and Bucket.
  3. package oss
  4. import (
  5. "bytes"
  6. "encoding/xml"
  7. "io"
  8. "net/http"
  9. "strings"
  10. "time"
  11. )
  12. // Client SDK's entry point. It's for bucket related options such as create/delete/set bucket (such as set/get ACL/lifecycle/referer/logging/website).
  13. // Object related operations are done by Bucket class.
  14. // Users use oss.New to create Client instance.
  15. //
  16. type (
  17. // Client OSS client
  18. Client struct {
  19. Config *Config // OSS client configuration
  20. Conn *Conn // Send HTTP request
  21. HTTPClient *http.Client //http.Client to use - if nil will make its own
  22. }
  23. // ClientOption client option such as UseCname, Timeout, SecurityToken.
  24. ClientOption func(*Client)
  25. )
  26. // New creates a new client.
  27. //
  28. // endpoint the OSS datacenter endpoint such as http://oss-cn-hangzhou.aliyuncs.com .
  29. // accessKeyId access key Id.
  30. // accessKeySecret access key secret.
  31. //
  32. // Client creates the new client instance, the returned value is valid when error is nil.
  33. // error it's nil if no error, otherwise it's an error object.
  34. //
  35. func New(endpoint, accessKeyID, accessKeySecret string, options ...ClientOption) (*Client, error) {
  36. // Configuration
  37. config := getDefaultOssConfig()
  38. config.Endpoint = endpoint
  39. config.AccessKeyID = accessKeyID
  40. config.AccessKeySecret = accessKeySecret
  41. // URL parse
  42. url := &urlMaker{}
  43. url.Init(config.Endpoint, config.IsCname, config.IsUseProxy)
  44. // HTTP connect
  45. conn := &Conn{config: config, url: url}
  46. // OSS client
  47. client := &Client{
  48. Config: config,
  49. Conn: conn,
  50. }
  51. // Client options parse
  52. for _, option := range options {
  53. option(client)
  54. }
  55. // Create HTTP connection
  56. err := conn.init(config, url, client.HTTPClient)
  57. return client, err
  58. }
  59. // Bucket gets the bucket instance.
  60. //
  61. // bucketName the bucket name.
  62. // Bucket the bucket object, when error is nil.
  63. //
  64. // error it's nil if no error, otherwise it's an error object.
  65. //
  66. func (client Client) Bucket(bucketName string) (*Bucket, error) {
  67. return &Bucket{
  68. client,
  69. bucketName,
  70. }, nil
  71. }
  72. // CreateBucket creates a bucket.
  73. //
  74. // bucketName the bucket name, it's globably unique and immutable. The bucket name can only consist of lowercase letters, numbers and dash ('-').
  75. // It must start with lowercase letter or number and the length can only be between 3 and 255.
  76. // options options for creating the bucket, with optional ACL. The ACL could be ACLPrivate, ACLPublicRead, and ACLPublicReadWrite. By default it's ACLPrivate.
  77. // It could also be specified with StorageClass option, which supports StorageStandard, StorageIA(infrequent access), StorageArchive.
  78. //
  79. // error it's nil if no error, otherwise it's an error object.
  80. //
  81. func (client Client) CreateBucket(bucketName string, options ...Option) error {
  82. headers := make(map[string]string)
  83. handleOptions(headers, options)
  84. buffer := new(bytes.Buffer)
  85. isOptSet, val, _ := isOptionSet(options, storageClass)
  86. if isOptSet {
  87. cbConfig := createBucketConfiguration{StorageClass: val.(StorageClassType)}
  88. bs, err := xml.Marshal(cbConfig)
  89. if err != nil {
  90. return err
  91. }
  92. buffer.Write(bs)
  93. contentType := http.DetectContentType(buffer.Bytes())
  94. headers[HTTPHeaderContentType] = contentType
  95. }
  96. params := map[string]interface{}{}
  97. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  98. if err != nil {
  99. return err
  100. }
  101. defer resp.Body.Close()
  102. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  103. }
  104. // ListBuckets lists buckets of the current account under the given endpoint, with optional filters.
  105. //
  106. // options specifies the filters such as Prefix, Marker and MaxKeys. Prefix is the bucket name's prefix filter.
  107. // And marker makes sure the returned buckets' name are greater than it in lexicographic order.
  108. // Maxkeys limits the max keys to return, and by default it's 100 and up to 1000.
  109. // For the common usage scenario, please check out list_bucket.go in the sample.
  110. // ListBucketsResponse the response object if error is nil.
  111. //
  112. // error it's nil if no error, otherwise it's an error object.
  113. //
  114. func (client Client) ListBuckets(options ...Option) (ListBucketsResult, error) {
  115. var out ListBucketsResult
  116. params, err := getRawParams(options)
  117. if err != nil {
  118. return out, err
  119. }
  120. resp, err := client.do("GET", "", params, nil, nil)
  121. if err != nil {
  122. return out, err
  123. }
  124. defer resp.Body.Close()
  125. err = xmlUnmarshal(resp.Body, &out)
  126. return out, err
  127. }
  128. // IsBucketExist checks if the bucket exists
  129. //
  130. // bucketName the bucket name.
  131. //
  132. // bool true if it exists, and it's only valid when error is nil.
  133. // error it's nil if no error, otherwise it's an error object.
  134. //
  135. func (client Client) IsBucketExist(bucketName string) (bool, error) {
  136. listRes, err := client.ListBuckets(Prefix(bucketName), MaxKeys(1))
  137. if err != nil {
  138. return false, err
  139. }
  140. if len(listRes.Buckets) == 1 && listRes.Buckets[0].Name == bucketName {
  141. return true, nil
  142. }
  143. return false, nil
  144. }
  145. // DeleteBucket deletes the bucket. Only empty bucket can be deleted (no object and parts).
  146. //
  147. // bucketName the bucket name.
  148. //
  149. // error it's nil if no error, otherwise it's an error object.
  150. //
  151. func (client Client) DeleteBucket(bucketName string) error {
  152. params := map[string]interface{}{}
  153. resp, err := client.do("DELETE", bucketName, params, nil, nil)
  154. if err != nil {
  155. return err
  156. }
  157. defer resp.Body.Close()
  158. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  159. }
  160. // GetBucketLocation gets the bucket location.
  161. //
  162. // Checks out the following link for more information :
  163. // https://help.aliyun.com/document_detail/oss/user_guide/oss_concept/endpoint.html
  164. //
  165. // bucketName the bucket name
  166. //
  167. // string bucket's datacenter location
  168. // error it's nil if no error, otherwise it's an error object.
  169. //
  170. func (client Client) GetBucketLocation(bucketName string) (string, error) {
  171. params := map[string]interface{}{}
  172. params["location"] = nil
  173. resp, err := client.do("GET", bucketName, params, nil, nil)
  174. if err != nil {
  175. return "", err
  176. }
  177. defer resp.Body.Close()
  178. var LocationConstraint string
  179. err = xmlUnmarshal(resp.Body, &LocationConstraint)
  180. return LocationConstraint, err
  181. }
  182. // SetBucketACL sets bucket's ACL.
  183. //
  184. // bucketName the bucket name
  185. // bucketAcl the bucket ACL: ACLPrivate, ACLPublicRead and ACLPublicReadWrite.
  186. //
  187. // error it's nil if no error, otherwise it's an error object.
  188. //
  189. func (client Client) SetBucketACL(bucketName string, bucketACL ACLType) error {
  190. headers := map[string]string{HTTPHeaderOssACL: string(bucketACL)}
  191. params := map[string]interface{}{}
  192. resp, err := client.do("PUT", bucketName, params, headers, nil)
  193. if err != nil {
  194. return err
  195. }
  196. defer resp.Body.Close()
  197. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  198. }
  199. // GetBucketACL gets the bucket ACL.
  200. //
  201. // bucketName the bucket name.
  202. //
  203. // GetBucketAclResponse the result object, and it's only valid when error is nil.
  204. // error it's nil if no error, otherwise it's an error object.
  205. //
  206. func (client Client) GetBucketACL(bucketName string) (GetBucketACLResult, error) {
  207. var out GetBucketACLResult
  208. params := map[string]interface{}{}
  209. params["acl"] = nil
  210. resp, err := client.do("GET", bucketName, params, nil, nil)
  211. if err != nil {
  212. return out, err
  213. }
  214. defer resp.Body.Close()
  215. err = xmlUnmarshal(resp.Body, &out)
  216. return out, err
  217. }
  218. // SetBucketLifecycle sets the bucket's lifecycle.
  219. //
  220. // For more information, checks out following link:
  221. // https://help.aliyun.com/document_detail/oss/user_guide/manage_object/object_lifecycle.html
  222. //
  223. // bucketName the bucket name.
  224. // rules the lifecycle rules. There're two kind of rules: absolute time expiration and relative time expiration in days and day/month/year respectively.
  225. // Check out sample/bucket_lifecycle.go for more details.
  226. //
  227. // error it's nil if no error, otherwise it's an error object.
  228. //
  229. func (client Client) SetBucketLifecycle(bucketName string, rules []LifecycleRule) error {
  230. lxml := lifecycleXML{Rules: convLifecycleRule(rules)}
  231. bs, err := xml.Marshal(lxml)
  232. if err != nil {
  233. return err
  234. }
  235. buffer := new(bytes.Buffer)
  236. buffer.Write(bs)
  237. contentType := http.DetectContentType(buffer.Bytes())
  238. headers := map[string]string{}
  239. headers[HTTPHeaderContentType] = contentType
  240. params := map[string]interface{}{}
  241. params["lifecycle"] = nil
  242. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  243. if err != nil {
  244. return err
  245. }
  246. defer resp.Body.Close()
  247. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  248. }
  249. // DeleteBucketLifecycle deletes the bucket's lifecycle.
  250. //
  251. //
  252. // bucketName the bucket name.
  253. //
  254. // error it's nil if no error, otherwise it's an error object.
  255. //
  256. func (client Client) DeleteBucketLifecycle(bucketName string) error {
  257. params := map[string]interface{}{}
  258. params["lifecycle"] = nil
  259. resp, err := client.do("DELETE", bucketName, params, nil, nil)
  260. if err != nil {
  261. return err
  262. }
  263. defer resp.Body.Close()
  264. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  265. }
  266. // GetBucketLifecycle gets the bucket's lifecycle settings.
  267. //
  268. // bucketName the bucket name.
  269. //
  270. // GetBucketLifecycleResponse the result object upon successful request. It's only valid when error is nil.
  271. // error it's nil if no error, otherwise it's an error object.
  272. //
  273. func (client Client) GetBucketLifecycle(bucketName string) (GetBucketLifecycleResult, error) {
  274. var out GetBucketLifecycleResult
  275. params := map[string]interface{}{}
  276. params["lifecycle"] = nil
  277. resp, err := client.do("GET", bucketName, params, nil, nil)
  278. if err != nil {
  279. return out, err
  280. }
  281. defer resp.Body.Close()
  282. err = xmlUnmarshal(resp.Body, &out)
  283. return out, err
  284. }
  285. // SetBucketReferer sets the bucket's referer whitelist and the flag if allowing empty referrer.
  286. //
  287. // To avoid stealing link on OSS data, OSS supports the HTTP referrer header. A whitelist referrer could be set either by API or web console, as well as
  288. // the allowing empty referrer flag. Note that this applies to requests from webbrowser only.
  289. // For example, for a bucket os-example and its referrer http://www.aliyun.com, all requests from this URL could access the bucket.
  290. // For more information, please check out this link :
  291. // https://help.aliyun.com/document_detail/oss/user_guide/security_management/referer.html
  292. //
  293. // bucketName the bucket name.
  294. // referers the referrer white list. A bucket could have a referrer list and each referrer supports one '*' and multiple '?' as wildcards.
  295. // The sample could be found in sample/bucket_referer.go
  296. // allowEmptyReferer the flag of allowing empty referrer. By default it's true.
  297. //
  298. // error it's nil if no error, otherwise it's an error object.
  299. //
  300. func (client Client) SetBucketReferer(bucketName string, referers []string, allowEmptyReferer bool) error {
  301. rxml := RefererXML{}
  302. rxml.AllowEmptyReferer = allowEmptyReferer
  303. if referers == nil {
  304. rxml.RefererList = append(rxml.RefererList, "")
  305. } else {
  306. for _, referer := range referers {
  307. rxml.RefererList = append(rxml.RefererList, referer)
  308. }
  309. }
  310. bs, err := xml.Marshal(rxml)
  311. if err != nil {
  312. return err
  313. }
  314. buffer := new(bytes.Buffer)
  315. buffer.Write(bs)
  316. contentType := http.DetectContentType(buffer.Bytes())
  317. headers := map[string]string{}
  318. headers[HTTPHeaderContentType] = contentType
  319. params := map[string]interface{}{}
  320. params["referer"] = nil
  321. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  322. if err != nil {
  323. return err
  324. }
  325. defer resp.Body.Close()
  326. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  327. }
  328. // GetBucketReferer gets the bucket's referrer white list.
  329. //
  330. // bucketName the bucket name.
  331. //
  332. // GetBucketRefererResponse the result object upon successful request. It's only valid when error is nil.
  333. // error it's nil if no error, otherwise it's an error object.
  334. //
  335. func (client Client) GetBucketReferer(bucketName string) (GetBucketRefererResult, error) {
  336. var out GetBucketRefererResult
  337. params := map[string]interface{}{}
  338. params["referer"] = nil
  339. resp, err := client.do("GET", bucketName, params, nil, nil)
  340. if err != nil {
  341. return out, err
  342. }
  343. defer resp.Body.Close()
  344. err = xmlUnmarshal(resp.Body, &out)
  345. return out, err
  346. }
  347. // SetBucketLogging sets the bucket logging settings.
  348. //
  349. // OSS could automatically store the access log. Only the bucket owner could enable the logging.
  350. // Once enabled, OSS would save all the access log into hourly log files in a specified bucket.
  351. // For more information, please check out https://help.aliyun.com/document_detail/oss/user_guide/security_management/logging.html
  352. //
  353. // bucketName bucket name to enable the log.
  354. // targetBucket the target bucket name to store the log files.
  355. // targetPrefix the log files' prefix.
  356. //
  357. // error it's nil if no error, otherwise it's an error object.
  358. //
  359. func (client Client) SetBucketLogging(bucketName, targetBucket, targetPrefix string,
  360. isEnable bool) error {
  361. var err error
  362. var bs []byte
  363. if isEnable {
  364. lxml := LoggingXML{}
  365. lxml.LoggingEnabled.TargetBucket = targetBucket
  366. lxml.LoggingEnabled.TargetPrefix = targetPrefix
  367. bs, err = xml.Marshal(lxml)
  368. } else {
  369. lxml := loggingXMLEmpty{}
  370. bs, err = xml.Marshal(lxml)
  371. }
  372. if err != nil {
  373. return err
  374. }
  375. buffer := new(bytes.Buffer)
  376. buffer.Write(bs)
  377. contentType := http.DetectContentType(buffer.Bytes())
  378. headers := map[string]string{}
  379. headers[HTTPHeaderContentType] = contentType
  380. params := map[string]interface{}{}
  381. params["logging"] = nil
  382. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  383. if err != nil {
  384. return err
  385. }
  386. defer resp.Body.Close()
  387. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  388. }
  389. // DeleteBucketLogging deletes the logging configuration to disable the logging on the bucket.
  390. //
  391. // bucketName the bucket name to disable the logging.
  392. //
  393. // error it's nil if no error, otherwise it's an error object.
  394. //
  395. func (client Client) DeleteBucketLogging(bucketName string) error {
  396. params := map[string]interface{}{}
  397. params["logging"] = nil
  398. resp, err := client.do("DELETE", bucketName, params, nil, nil)
  399. if err != nil {
  400. return err
  401. }
  402. defer resp.Body.Close()
  403. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  404. }
  405. // GetBucketLogging gets the bucket's logging settings
  406. //
  407. // bucketName the bucket name
  408. // GetBucketLoggingResponse the result object upon successful request. It's only valid when error is nil.
  409. //
  410. // error it's nil if no error, otherwise it's an error object.
  411. //
  412. func (client Client) GetBucketLogging(bucketName string) (GetBucketLoggingResult, error) {
  413. var out GetBucketLoggingResult
  414. params := map[string]interface{}{}
  415. params["logging"] = nil
  416. resp, err := client.do("GET", bucketName, params, nil, nil)
  417. if err != nil {
  418. return out, err
  419. }
  420. defer resp.Body.Close()
  421. err = xmlUnmarshal(resp.Body, &out)
  422. return out, err
  423. }
  424. // SetBucketWebsite sets the bucket's static website's index and error page.
  425. //
  426. // OSS supports static web site hosting for the bucket data. When the bucket is enabled with that, you can access the file in the bucket like the way to access a static website.
  427. // For more information, please check out: https://help.aliyun.com/document_detail/oss/user_guide/static_host_website.html
  428. //
  429. // bucketName the bucket name to enable static web site.
  430. // indexDocument index page.
  431. // errorDocument error page.
  432. //
  433. // error it's nil if no error, otherwise it's an error object.
  434. //
  435. func (client Client) SetBucketWebsite(bucketName, indexDocument, errorDocument string) error {
  436. wxml := WebsiteXML{}
  437. wxml.IndexDocument.Suffix = indexDocument
  438. wxml.ErrorDocument.Key = errorDocument
  439. bs, err := xml.Marshal(wxml)
  440. if err != nil {
  441. return err
  442. }
  443. buffer := new(bytes.Buffer)
  444. buffer.Write(bs)
  445. contentType := http.DetectContentType(buffer.Bytes())
  446. headers := make(map[string]string)
  447. headers[HTTPHeaderContentType] = contentType
  448. params := map[string]interface{}{}
  449. params["website"] = nil
  450. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  451. if err != nil {
  452. return err
  453. }
  454. defer resp.Body.Close()
  455. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  456. }
  457. // DeleteBucketWebsite deletes the bucket's static web site settings.
  458. //
  459. // bucketName the bucket name.
  460. //
  461. // error it's nil if no error, otherwise it's an error object.
  462. //
  463. func (client Client) DeleteBucketWebsite(bucketName string) error {
  464. params := map[string]interface{}{}
  465. params["website"] = nil
  466. resp, err := client.do("DELETE", bucketName, params, nil, nil)
  467. if err != nil {
  468. return err
  469. }
  470. defer resp.Body.Close()
  471. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  472. }
  473. // GetBucketWebsite gets the bucket's default page (index page) and the error page.
  474. //
  475. // bucketName the bucket name
  476. //
  477. // GetBucketWebsiteResponse the result object upon successful request. It's only valid when error is nil.
  478. // error it's nil if no error, otherwise it's an error object.
  479. //
  480. func (client Client) GetBucketWebsite(bucketName string) (GetBucketWebsiteResult, error) {
  481. var out GetBucketWebsiteResult
  482. params := map[string]interface{}{}
  483. params["website"] = nil
  484. resp, err := client.do("GET", bucketName, params, nil, nil)
  485. if err != nil {
  486. return out, err
  487. }
  488. defer resp.Body.Close()
  489. err = xmlUnmarshal(resp.Body, &out)
  490. return out, err
  491. }
  492. // SetBucketCORS sets the bucket's CORS rules
  493. //
  494. // For more information, please check out https://help.aliyun.com/document_detail/oss/user_guide/security_management/cors.html
  495. //
  496. // bucketName the bucket name
  497. // corsRules the CORS rules to set. The related sample code is in sample/bucket_cors.go.
  498. //
  499. // error it's nil if no error, otherwise it's an error object.
  500. //
  501. func (client Client) SetBucketCORS(bucketName string, corsRules []CORSRule) error {
  502. corsxml := CORSXML{}
  503. for _, v := range corsRules {
  504. cr := CORSRule{}
  505. cr.AllowedMethod = v.AllowedMethod
  506. cr.AllowedOrigin = v.AllowedOrigin
  507. cr.AllowedHeader = v.AllowedHeader
  508. cr.ExposeHeader = v.ExposeHeader
  509. cr.MaxAgeSeconds = v.MaxAgeSeconds
  510. corsxml.CORSRules = append(corsxml.CORSRules, cr)
  511. }
  512. bs, err := xml.Marshal(corsxml)
  513. if err != nil {
  514. return err
  515. }
  516. buffer := new(bytes.Buffer)
  517. buffer.Write(bs)
  518. contentType := http.DetectContentType(buffer.Bytes())
  519. headers := map[string]string{}
  520. headers[HTTPHeaderContentType] = contentType
  521. params := map[string]interface{}{}
  522. params["cors"] = nil
  523. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  524. if err != nil {
  525. return err
  526. }
  527. defer resp.Body.Close()
  528. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  529. }
  530. // DeleteBucketCORS deletes the bucket's static website settings.
  531. //
  532. // bucketName the bucket name.
  533. //
  534. // error it's nil if no error, otherwise it's an error object.
  535. //
  536. func (client Client) DeleteBucketCORS(bucketName string) error {
  537. params := map[string]interface{}{}
  538. params["cors"] = nil
  539. resp, err := client.do("DELETE", bucketName, params, nil, nil)
  540. if err != nil {
  541. return err
  542. }
  543. defer resp.Body.Close()
  544. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  545. }
  546. // GetBucketCORS gets the bucket's CORS settings.
  547. //
  548. // bucketName the bucket name.
  549. // GetBucketCORSResult the result object upon successful request. It's only valid when error is nil.
  550. //
  551. // error it's nil if no error, otherwise it's an error object.
  552. //
  553. func (client Client) GetBucketCORS(bucketName string) (GetBucketCORSResult, error) {
  554. var out GetBucketCORSResult
  555. params := map[string]interface{}{}
  556. params["cors"] = nil
  557. resp, err := client.do("GET", bucketName, params, nil, nil)
  558. if err != nil {
  559. return out, err
  560. }
  561. defer resp.Body.Close()
  562. err = xmlUnmarshal(resp.Body, &out)
  563. return out, err
  564. }
  565. // GetBucketInfo gets the bucket information.
  566. //
  567. // bucketName the bucket name.
  568. // GetBucketInfoResult the result object upon successful request. It's only valid when error is nil.
  569. //
  570. // error it's nil if no error, otherwise it's an error object.
  571. //
  572. func (client Client) GetBucketInfo(bucketName string) (GetBucketInfoResult, error) {
  573. var out GetBucketInfoResult
  574. params := map[string]interface{}{}
  575. params["bucketInfo"] = nil
  576. resp, err := client.do("GET", bucketName, params, nil, nil)
  577. if err != nil {
  578. return out, err
  579. }
  580. defer resp.Body.Close()
  581. err = xmlUnmarshal(resp.Body, &out)
  582. return out, err
  583. }
  584. // UseCname sets the flag of using CName. By default it's false.
  585. //
  586. // isUseCname true: the endpoint has the CName, false: the endpoint does not have cname. Default is false.
  587. //
  588. func UseCname(isUseCname bool) ClientOption {
  589. return func(client *Client) {
  590. client.Config.IsCname = isUseCname
  591. client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
  592. }
  593. }
  594. // Timeout sets the HTTP timeout in seconds.
  595. //
  596. // connectTimeoutSec HTTP timeout in seconds. Default is 10 seconds. 0 means infinite (not recommended)
  597. // readWriteTimeout HTTP read or write's timeout in seconds. Default is 20 seconds. 0 means infinite.
  598. //
  599. func Timeout(connectTimeoutSec, readWriteTimeout int64) ClientOption {
  600. return func(client *Client) {
  601. client.Config.HTTPTimeout.ConnectTimeout =
  602. time.Second * time.Duration(connectTimeoutSec)
  603. client.Config.HTTPTimeout.ReadWriteTimeout =
  604. time.Second * time.Duration(readWriteTimeout)
  605. client.Config.HTTPTimeout.HeaderTimeout =
  606. time.Second * time.Duration(readWriteTimeout)
  607. client.Config.HTTPTimeout.IdleConnTimeout =
  608. time.Second * time.Duration(readWriteTimeout)
  609. client.Config.HTTPTimeout.LongTimeout =
  610. time.Second * time.Duration(readWriteTimeout*10)
  611. }
  612. }
  613. // SecurityToken sets the temporary user's SecurityToken.
  614. //
  615. // token STS token
  616. //
  617. func SecurityToken(token string) ClientOption {
  618. return func(client *Client) {
  619. client.Config.SecurityToken = strings.TrimSpace(token)
  620. }
  621. }
  622. // EnableMD5 enables MD5 validation.
  623. //
  624. // isEnableMD5 true: enable MD5 validation; false: disable MD5 validation.
  625. //
  626. func EnableMD5(isEnableMD5 bool) ClientOption {
  627. return func(client *Client) {
  628. client.Config.IsEnableMD5 = isEnableMD5
  629. }
  630. }
  631. // MD5ThresholdCalcInMemory sets the memory usage threshold for computing the MD5, default is 16MB.
  632. //
  633. // threshold the memory threshold in bytes. When the uploaded content is more than 16MB, the temp file is used for computing the MD5.
  634. //
  635. func MD5ThresholdCalcInMemory(threshold int64) ClientOption {
  636. return func(client *Client) {
  637. client.Config.MD5Threshold = threshold
  638. }
  639. }
  640. // EnableCRC enables the CRC checksum. Default is true.
  641. //
  642. // isEnableCRC true: enable CRC checksum; false: disable the CRC checksum.
  643. //
  644. func EnableCRC(isEnableCRC bool) ClientOption {
  645. return func(client *Client) {
  646. client.Config.IsEnableCRC = isEnableCRC
  647. }
  648. }
  649. // UserAgent specifies UserAgent. The default is aliyun-sdk-go/1.2.0 (windows/-/amd64;go1.5.2).
  650. //
  651. // userAgent the user agent string.
  652. //
  653. func UserAgent(userAgent string) ClientOption {
  654. return func(client *Client) {
  655. client.Config.UserAgent = userAgent
  656. }
  657. }
  658. // Proxy sets the proxy (optional). The default is not using proxy.
  659. //
  660. // proxyHost the proxy host in the format "host:port". For example, proxy.com:80 .
  661. //
  662. func Proxy(proxyHost string) ClientOption {
  663. return func(client *Client) {
  664. client.Config.IsUseProxy = true
  665. client.Config.ProxyHost = proxyHost
  666. client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
  667. }
  668. }
  669. // AuthProxy sets the proxy information with user name and password.
  670. //
  671. // proxyHost the proxy host in the format "host:port". For example, proxy.com:80 .
  672. // proxyUser the proxy user name.
  673. // proxyPassword the proxy password.
  674. //
  675. func AuthProxy(proxyHost, proxyUser, proxyPassword string) ClientOption {
  676. return func(client *Client) {
  677. client.Config.IsUseProxy = true
  678. client.Config.ProxyHost = proxyHost
  679. client.Config.IsAuthProxy = true
  680. client.Config.ProxyUser = proxyUser
  681. client.Config.ProxyPassword = proxyPassword
  682. client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
  683. }
  684. }
  685. //
  686. // HTTPClient sets the http.Client in use to the one passed in
  687. //
  688. func HTTPClient(HTTPClient *http.Client) ClientOption {
  689. return func(client *Client) {
  690. client.HTTPClient = HTTPClient
  691. }
  692. }
  693. // Private
  694. func (client Client) do(method, bucketName string, params map[string]interface{},
  695. headers map[string]string, data io.Reader) (*Response, error) {
  696. return client.Conn.Do(method, bucketName, "", params,
  697. headers, data, 0, nil)
  698. }