client.go 25 KB

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