client.go 24 KB

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