client.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  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. params["acl"] = nil
  195. resp, err := client.do("PUT", bucketName, params, headers, nil)
  196. if err != nil {
  197. return err
  198. }
  199. defer resp.Body.Close()
  200. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  201. }
  202. // GetBucketACL gets the bucket ACL.
  203. //
  204. // bucketName the bucket name.
  205. //
  206. // GetBucketAclResponse the result object, and it's only valid when error is nil.
  207. // error it's nil if no error, otherwise it's an error object.
  208. //
  209. func (client Client) GetBucketACL(bucketName string) (GetBucketACLResult, error) {
  210. var out GetBucketACLResult
  211. params := map[string]interface{}{}
  212. params["acl"] = nil
  213. resp, err := client.do("GET", bucketName, params, nil, nil)
  214. if err != nil {
  215. return out, err
  216. }
  217. defer resp.Body.Close()
  218. err = xmlUnmarshal(resp.Body, &out)
  219. return out, err
  220. }
  221. // SetBucketLifecycle sets the bucket's lifecycle.
  222. //
  223. // For more information, checks out following link:
  224. // https://help.aliyun.com/document_detail/oss/user_guide/manage_object/object_lifecycle.html
  225. //
  226. // bucketName the bucket name.
  227. // rules the lifecycle rules. There're two kind of rules: absolute time expiration and relative time expiration in days and day/month/year respectively.
  228. // Check out sample/bucket_lifecycle.go for more details.
  229. //
  230. // error it's nil if no error, otherwise it's an error object.
  231. //
  232. func (client Client) SetBucketLifecycle(bucketName string, rules []LifecycleRule) error {
  233. err := verifyLifecycleRules(rules)
  234. if err != nil {
  235. return err
  236. }
  237. lifecycleCfg := LifecycleConfiguration{Rules: rules}
  238. bs, err := xml.Marshal(lifecycleCfg)
  239. if err != nil {
  240. return err
  241. }
  242. buffer := new(bytes.Buffer)
  243. buffer.Write(bs)
  244. contentType := http.DetectContentType(buffer.Bytes())
  245. headers := map[string]string{}
  246. headers[HTTPHeaderContentType] = contentType
  247. params := map[string]interface{}{}
  248. params["lifecycle"] = nil
  249. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  250. if err != nil {
  251. return err
  252. }
  253. defer resp.Body.Close()
  254. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  255. }
  256. // DeleteBucketLifecycle deletes the bucket's lifecycle.
  257. //
  258. //
  259. // bucketName the bucket name.
  260. //
  261. // error it's nil if no error, otherwise it's an error object.
  262. //
  263. func (client Client) DeleteBucketLifecycle(bucketName string) error {
  264. params := map[string]interface{}{}
  265. params["lifecycle"] = nil
  266. resp, err := client.do("DELETE", bucketName, params, nil, nil)
  267. if err != nil {
  268. return err
  269. }
  270. defer resp.Body.Close()
  271. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  272. }
  273. // GetBucketLifecycle gets the bucket's lifecycle settings.
  274. //
  275. // bucketName the bucket name.
  276. //
  277. // GetBucketLifecycleResponse the result object upon successful request. It's only valid when error is nil.
  278. // error it's nil if no error, otherwise it's an error object.
  279. //
  280. func (client Client) GetBucketLifecycle(bucketName string) (GetBucketLifecycleResult, error) {
  281. var out GetBucketLifecycleResult
  282. params := map[string]interface{}{}
  283. params["lifecycle"] = nil
  284. resp, err := client.do("GET", bucketName, params, nil, nil)
  285. if err != nil {
  286. return out, err
  287. }
  288. defer resp.Body.Close()
  289. err = xmlUnmarshal(resp.Body, &out)
  290. return out, err
  291. }
  292. // SetBucketReferer sets the bucket's referer whitelist and the flag if allowing empty referrer.
  293. //
  294. // 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
  295. // the allowing empty referrer flag. Note that this applies to requests from webbrowser only.
  296. // For example, for a bucket os-example and its referrer http://www.aliyun.com, all requests from this URL could access the bucket.
  297. // For more information, please check out this link :
  298. // https://help.aliyun.com/document_detail/oss/user_guide/security_management/referer.html
  299. //
  300. // bucketName the bucket name.
  301. // referers the referrer white list. A bucket could have a referrer list and each referrer supports one '*' and multiple '?' as wildcards.
  302. // The sample could be found in sample/bucket_referer.go
  303. // allowEmptyReferer the flag of allowing empty referrer. By default it's true.
  304. //
  305. // error it's nil if no error, otherwise it's an error object.
  306. //
  307. func (client Client) SetBucketReferer(bucketName string, referers []string, allowEmptyReferer bool) error {
  308. rxml := RefererXML{}
  309. rxml.AllowEmptyReferer = allowEmptyReferer
  310. if referers == nil {
  311. rxml.RefererList = append(rxml.RefererList, "")
  312. } else {
  313. for _, referer := range referers {
  314. rxml.RefererList = append(rxml.RefererList, referer)
  315. }
  316. }
  317. bs, err := xml.Marshal(rxml)
  318. if err != nil {
  319. return err
  320. }
  321. buffer := new(bytes.Buffer)
  322. buffer.Write(bs)
  323. contentType := http.DetectContentType(buffer.Bytes())
  324. headers := map[string]string{}
  325. headers[HTTPHeaderContentType] = contentType
  326. params := map[string]interface{}{}
  327. params["referer"] = nil
  328. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  329. if err != nil {
  330. return err
  331. }
  332. defer resp.Body.Close()
  333. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  334. }
  335. // GetBucketReferer gets the bucket's referrer white list.
  336. //
  337. // bucketName the bucket name.
  338. //
  339. // GetBucketRefererResponse the result object upon successful request. It's only valid when error is nil.
  340. // error it's nil if no error, otherwise it's an error object.
  341. //
  342. func (client Client) GetBucketReferer(bucketName string) (GetBucketRefererResult, error) {
  343. var out GetBucketRefererResult
  344. params := map[string]interface{}{}
  345. params["referer"] = nil
  346. resp, err := client.do("GET", bucketName, params, nil, nil)
  347. if err != nil {
  348. return out, err
  349. }
  350. defer resp.Body.Close()
  351. err = xmlUnmarshal(resp.Body, &out)
  352. return out, err
  353. }
  354. // SetBucketLogging sets the bucket logging settings.
  355. //
  356. // OSS could automatically store the access log. Only the bucket owner could enable the logging.
  357. // Once enabled, OSS would save all the access log into hourly log files in a specified bucket.
  358. // For more information, please check out https://help.aliyun.com/document_detail/oss/user_guide/security_management/logging.html
  359. //
  360. // bucketName bucket name to enable the log.
  361. // targetBucket the target bucket name to store the log files.
  362. // targetPrefix the log files' prefix.
  363. //
  364. // error it's nil if no error, otherwise it's an error object.
  365. //
  366. func (client Client) SetBucketLogging(bucketName, targetBucket, targetPrefix string,
  367. isEnable bool) error {
  368. var err error
  369. var bs []byte
  370. if isEnable {
  371. lxml := LoggingXML{}
  372. lxml.LoggingEnabled.TargetBucket = targetBucket
  373. lxml.LoggingEnabled.TargetPrefix = targetPrefix
  374. bs, err = xml.Marshal(lxml)
  375. } else {
  376. lxml := loggingXMLEmpty{}
  377. bs, err = xml.Marshal(lxml)
  378. }
  379. if err != nil {
  380. return err
  381. }
  382. buffer := new(bytes.Buffer)
  383. buffer.Write(bs)
  384. contentType := http.DetectContentType(buffer.Bytes())
  385. headers := map[string]string{}
  386. headers[HTTPHeaderContentType] = contentType
  387. params := map[string]interface{}{}
  388. params["logging"] = nil
  389. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  390. if err != nil {
  391. return err
  392. }
  393. defer resp.Body.Close()
  394. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  395. }
  396. // DeleteBucketLogging deletes the logging configuration to disable the logging on the bucket.
  397. //
  398. // bucketName the bucket name to disable the logging.
  399. //
  400. // error it's nil if no error, otherwise it's an error object.
  401. //
  402. func (client Client) DeleteBucketLogging(bucketName string) error {
  403. params := map[string]interface{}{}
  404. params["logging"] = nil
  405. resp, err := client.do("DELETE", bucketName, params, nil, nil)
  406. if err != nil {
  407. return err
  408. }
  409. defer resp.Body.Close()
  410. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  411. }
  412. // GetBucketLogging gets the bucket's logging settings
  413. //
  414. // bucketName the bucket name
  415. // GetBucketLoggingResponse the result object upon successful request. It's only valid when error is nil.
  416. //
  417. // error it's nil if no error, otherwise it's an error object.
  418. //
  419. func (client Client) GetBucketLogging(bucketName string) (GetBucketLoggingResult, error) {
  420. var out GetBucketLoggingResult
  421. params := map[string]interface{}{}
  422. params["logging"] = nil
  423. resp, err := client.do("GET", bucketName, params, nil, nil)
  424. if err != nil {
  425. return out, err
  426. }
  427. defer resp.Body.Close()
  428. err = xmlUnmarshal(resp.Body, &out)
  429. return out, err
  430. }
  431. // SetBucketWebsite sets the bucket's static website's index and error page.
  432. //
  433. // 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.
  434. // For more information, please check out: https://help.aliyun.com/document_detail/oss/user_guide/static_host_website.html
  435. //
  436. // bucketName the bucket name to enable static web site.
  437. // indexDocument index page.
  438. // errorDocument error page.
  439. //
  440. // error it's nil if no error, otherwise it's an error object.
  441. //
  442. func (client Client) SetBucketWebsite(bucketName, indexDocument, errorDocument string) error {
  443. wxml := WebsiteXML{}
  444. wxml.IndexDocument.Suffix = indexDocument
  445. wxml.ErrorDocument.Key = errorDocument
  446. bs, err := xml.Marshal(wxml)
  447. if err != nil {
  448. return err
  449. }
  450. buffer := new(bytes.Buffer)
  451. buffer.Write(bs)
  452. contentType := http.DetectContentType(buffer.Bytes())
  453. headers := make(map[string]string)
  454. headers[HTTPHeaderContentType] = contentType
  455. params := map[string]interface{}{}
  456. params["website"] = nil
  457. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  458. if err != nil {
  459. return err
  460. }
  461. defer resp.Body.Close()
  462. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  463. }
  464. // DeleteBucketWebsite deletes the bucket's static web site settings.
  465. //
  466. // bucketName the bucket name.
  467. //
  468. // error it's nil if no error, otherwise it's an error object.
  469. //
  470. func (client Client) DeleteBucketWebsite(bucketName string) error {
  471. params := map[string]interface{}{}
  472. params["website"] = nil
  473. resp, err := client.do("DELETE", bucketName, params, nil, nil)
  474. if err != nil {
  475. return err
  476. }
  477. defer resp.Body.Close()
  478. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  479. }
  480. // GetBucketWebsite gets the bucket's default page (index page) and the error page.
  481. //
  482. // bucketName the bucket name
  483. //
  484. // GetBucketWebsiteResponse the result object upon successful request. It's only valid when error is nil.
  485. // error it's nil if no error, otherwise it's an error object.
  486. //
  487. func (client Client) GetBucketWebsite(bucketName string) (GetBucketWebsiteResult, error) {
  488. var out GetBucketWebsiteResult
  489. params := map[string]interface{}{}
  490. params["website"] = nil
  491. resp, err := client.do("GET", bucketName, params, nil, nil)
  492. if err != nil {
  493. return out, err
  494. }
  495. defer resp.Body.Close()
  496. err = xmlUnmarshal(resp.Body, &out)
  497. return out, err
  498. }
  499. // SetBucketCORS sets the bucket's CORS rules
  500. //
  501. // For more information, please check out https://help.aliyun.com/document_detail/oss/user_guide/security_management/cors.html
  502. //
  503. // bucketName the bucket name
  504. // corsRules the CORS rules to set. The related sample code is in sample/bucket_cors.go.
  505. //
  506. // error it's nil if no error, otherwise it's an error object.
  507. //
  508. func (client Client) SetBucketCORS(bucketName string, corsRules []CORSRule) error {
  509. corsxml := CORSXML{}
  510. for _, v := range corsRules {
  511. cr := CORSRule{}
  512. cr.AllowedMethod = v.AllowedMethod
  513. cr.AllowedOrigin = v.AllowedOrigin
  514. cr.AllowedHeader = v.AllowedHeader
  515. cr.ExposeHeader = v.ExposeHeader
  516. cr.MaxAgeSeconds = v.MaxAgeSeconds
  517. corsxml.CORSRules = append(corsxml.CORSRules, cr)
  518. }
  519. bs, err := xml.Marshal(corsxml)
  520. if err != nil {
  521. return err
  522. }
  523. buffer := new(bytes.Buffer)
  524. buffer.Write(bs)
  525. contentType := http.DetectContentType(buffer.Bytes())
  526. headers := map[string]string{}
  527. headers[HTTPHeaderContentType] = contentType
  528. params := map[string]interface{}{}
  529. params["cors"] = nil
  530. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  531. if err != nil {
  532. return err
  533. }
  534. defer resp.Body.Close()
  535. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  536. }
  537. // DeleteBucketCORS deletes the bucket's static website settings.
  538. //
  539. // bucketName the bucket name.
  540. //
  541. // error it's nil if no error, otherwise it's an error object.
  542. //
  543. func (client Client) DeleteBucketCORS(bucketName string) error {
  544. params := map[string]interface{}{}
  545. params["cors"] = nil
  546. resp, err := client.do("DELETE", bucketName, params, nil, nil)
  547. if err != nil {
  548. return err
  549. }
  550. defer resp.Body.Close()
  551. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  552. }
  553. // GetBucketCORS gets the bucket's CORS settings.
  554. //
  555. // bucketName the bucket name.
  556. // GetBucketCORSResult the result object upon successful request. It's only valid when error is nil.
  557. //
  558. // error it's nil if no error, otherwise it's an error object.
  559. //
  560. func (client Client) GetBucketCORS(bucketName string) (GetBucketCORSResult, error) {
  561. var out GetBucketCORSResult
  562. params := map[string]interface{}{}
  563. params["cors"] = nil
  564. resp, err := client.do("GET", bucketName, params, nil, nil)
  565. if err != nil {
  566. return out, err
  567. }
  568. defer resp.Body.Close()
  569. err = xmlUnmarshal(resp.Body, &out)
  570. return out, err
  571. }
  572. // GetBucketInfo gets the bucket information.
  573. //
  574. // bucketName the bucket name.
  575. // GetBucketInfoResult the result object upon successful request. It's only valid when error is nil.
  576. //
  577. // error it's nil if no error, otherwise it's an error object.
  578. //
  579. func (client Client) GetBucketInfo(bucketName string) (GetBucketInfoResult, error) {
  580. var out GetBucketInfoResult
  581. params := map[string]interface{}{}
  582. params["bucketInfo"] = nil
  583. resp, err := client.do("GET", bucketName, params, nil, nil)
  584. if err != nil {
  585. return out, err
  586. }
  587. defer resp.Body.Close()
  588. err = xmlUnmarshal(resp.Body, &out)
  589. // convert None to ""
  590. if err == nil {
  591. if out.BucketInfo.SseRule.KMSMasterKeyID == "None" {
  592. out.BucketInfo.SseRule.KMSMasterKeyID = ""
  593. }
  594. if out.BucketInfo.SseRule.SSEAlgorithm == "None" {
  595. out.BucketInfo.SseRule.SSEAlgorithm = ""
  596. }
  597. }
  598. return out, err
  599. }
  600. // SetBucketEncryption set bucket encryption config
  601. // bucketName the bucket name.
  602. // error it's nil if no error, otherwise it's an error object.
  603. func (client Client) SetBucketEncryption(bucketName string, encryptionRule ServerEncryptionRule) error {
  604. var err error
  605. var bs []byte
  606. bs, err = xml.Marshal(encryptionRule)
  607. if err != nil {
  608. return err
  609. }
  610. buffer := new(bytes.Buffer)
  611. buffer.Write(bs)
  612. contentType := http.DetectContentType(buffer.Bytes())
  613. headers := map[string]string{}
  614. headers[HTTPHeaderContentType] = contentType
  615. params := map[string]interface{}{}
  616. params["encryption"] = nil
  617. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  618. if err != nil {
  619. return err
  620. }
  621. defer resp.Body.Close()
  622. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  623. }
  624. // GetBucketEncryption get bucket encryption config
  625. // bucketName the bucket name.
  626. // error it's nil if no error, otherwise it's an error object.
  627. func (client Client) GetBucketEncryption(bucketName string) (GetBucketEncryptionResult, error) {
  628. var out GetBucketEncryptionResult
  629. params := map[string]interface{}{}
  630. params["encryption"] = nil
  631. resp, err := client.do("GET", bucketName, params, nil, nil)
  632. if err != nil {
  633. return out, err
  634. }
  635. defer resp.Body.Close()
  636. err = xmlUnmarshal(resp.Body, &out)
  637. return out, err
  638. }
  639. // DeleteBucketEncryption delete bucket encryption config
  640. // bucketName the bucket name.
  641. // error it's nil if no error, otherwise it's an error object.
  642. func (client Client) DeleteBucketEncryption(bucketName string) error {
  643. params := map[string]interface{}{}
  644. params["encryption"] = nil
  645. resp, err := client.do("DELETE", bucketName, params, nil, nil)
  646. if err != nil {
  647. return err
  648. }
  649. defer resp.Body.Close()
  650. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  651. }
  652. // GetBucketStat get bucket stat
  653. // bucketName the bucket name.
  654. // error it's nil if no error, otherwise it's an error object.
  655. func (client Client) GetBucketStat(bucketName string) (GetBucketStatResult, error) {
  656. var out GetBucketStatResult
  657. params := map[string]interface{}{}
  658. params["stat"] = nil
  659. resp, err := client.do("GET", bucketName, params, nil, nil)
  660. if err != nil {
  661. return out, err
  662. }
  663. defer resp.Body.Close()
  664. err = xmlUnmarshal(resp.Body, &out)
  665. return out, err
  666. }
  667. // LimitUploadSpeed set upload bandwidth limit speed,default is 0,unlimited
  668. // upSpeed KB/s, 0 is unlimited,default is 0
  669. // error it's nil if success, otherwise failure
  670. func (client Client) LimitUploadSpeed(upSpeed int) error {
  671. if client.Config == nil {
  672. return fmt.Errorf("client config is nil")
  673. }
  674. return client.Config.LimitUploadSpeed(upSpeed)
  675. }
  676. // UseCname sets the flag of using CName. By default it's false.
  677. //
  678. // isUseCname true: the endpoint has the CName, false: the endpoint does not have cname. Default is false.
  679. //
  680. func UseCname(isUseCname bool) ClientOption {
  681. return func(client *Client) {
  682. client.Config.IsCname = isUseCname
  683. client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
  684. }
  685. }
  686. // Timeout sets the HTTP timeout in seconds.
  687. //
  688. // connectTimeoutSec HTTP timeout in seconds. Default is 10 seconds. 0 means infinite (not recommended)
  689. // readWriteTimeout HTTP read or write's timeout in seconds. Default is 20 seconds. 0 means infinite.
  690. //
  691. func Timeout(connectTimeoutSec, readWriteTimeout int64) ClientOption {
  692. return func(client *Client) {
  693. client.Config.HTTPTimeout.ConnectTimeout =
  694. time.Second * time.Duration(connectTimeoutSec)
  695. client.Config.HTTPTimeout.ReadWriteTimeout =
  696. time.Second * time.Duration(readWriteTimeout)
  697. client.Config.HTTPTimeout.HeaderTimeout =
  698. time.Second * time.Duration(readWriteTimeout)
  699. client.Config.HTTPTimeout.IdleConnTimeout =
  700. time.Second * time.Duration(readWriteTimeout)
  701. client.Config.HTTPTimeout.LongTimeout =
  702. time.Second * time.Duration(readWriteTimeout*10)
  703. }
  704. }
  705. // SecurityToken sets the temporary user's SecurityToken.
  706. //
  707. // token STS token
  708. //
  709. func SecurityToken(token string) ClientOption {
  710. return func(client *Client) {
  711. client.Config.SecurityToken = strings.TrimSpace(token)
  712. }
  713. }
  714. // EnableMD5 enables MD5 validation.
  715. //
  716. // isEnableMD5 true: enable MD5 validation; false: disable MD5 validation.
  717. //
  718. func EnableMD5(isEnableMD5 bool) ClientOption {
  719. return func(client *Client) {
  720. client.Config.IsEnableMD5 = isEnableMD5
  721. }
  722. }
  723. // MD5ThresholdCalcInMemory sets the memory usage threshold for computing the MD5, default is 16MB.
  724. //
  725. // threshold the memory threshold in bytes. When the uploaded content is more than 16MB, the temp file is used for computing the MD5.
  726. //
  727. func MD5ThresholdCalcInMemory(threshold int64) ClientOption {
  728. return func(client *Client) {
  729. client.Config.MD5Threshold = threshold
  730. }
  731. }
  732. // EnableCRC enables the CRC checksum. Default is true.
  733. //
  734. // isEnableCRC true: enable CRC checksum; false: disable the CRC checksum.
  735. //
  736. func EnableCRC(isEnableCRC bool) ClientOption {
  737. return func(client *Client) {
  738. client.Config.IsEnableCRC = isEnableCRC
  739. }
  740. }
  741. // UserAgent specifies UserAgent. The default is aliyun-sdk-go/1.2.0 (windows/-/amd64;go1.5.2).
  742. //
  743. // userAgent the user agent string.
  744. //
  745. func UserAgent(userAgent string) ClientOption {
  746. return func(client *Client) {
  747. client.Config.UserAgent = userAgent
  748. }
  749. }
  750. // Proxy sets the proxy (optional). The default is not using proxy.
  751. //
  752. // proxyHost the proxy host in the format "host:port". For example, proxy.com:80 .
  753. //
  754. func Proxy(proxyHost string) ClientOption {
  755. return func(client *Client) {
  756. client.Config.IsUseProxy = true
  757. client.Config.ProxyHost = proxyHost
  758. client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
  759. }
  760. }
  761. // AuthProxy sets the proxy information with user name and password.
  762. //
  763. // proxyHost the proxy host in the format "host:port". For example, proxy.com:80 .
  764. // proxyUser the proxy user name.
  765. // proxyPassword the proxy password.
  766. //
  767. func AuthProxy(proxyHost, proxyUser, proxyPassword string) ClientOption {
  768. return func(client *Client) {
  769. client.Config.IsUseProxy = true
  770. client.Config.ProxyHost = proxyHost
  771. client.Config.IsAuthProxy = true
  772. client.Config.ProxyUser = proxyUser
  773. client.Config.ProxyPassword = proxyPassword
  774. client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
  775. }
  776. }
  777. //
  778. // HTTPClient sets the http.Client in use to the one passed in
  779. //
  780. func HTTPClient(HTTPClient *http.Client) ClientOption {
  781. return func(client *Client) {
  782. client.HTTPClient = HTTPClient
  783. }
  784. }
  785. //
  786. // SetLogLevel sets the oss sdk log level
  787. //
  788. func SetLogLevel(LogLevel int) ClientOption {
  789. return func(client *Client) {
  790. client.Config.LogLevel = LogLevel
  791. }
  792. }
  793. //
  794. // SetLogger sets the oss sdk logger
  795. //
  796. func SetLogger(Logger *log.Logger) ClientOption {
  797. return func(client *Client) {
  798. client.Config.Logger = Logger
  799. }
  800. }
  801. // Private
  802. func (client Client) do(method, bucketName string, params map[string]interface{},
  803. headers map[string]string, data io.Reader) (*Response, error) {
  804. return client.Conn.Do(method, bucketName, "", params,
  805. headers, data, 0, nil)
  806. }