client.go 24 KB

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