client.go 25 KB

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