client.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197
  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. "io/ioutil"
  10. "log"
  11. "net/http"
  12. "strings"
  13. "time"
  14. )
  15. // 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).
  16. // Object related operations are done by Bucket class.
  17. // Users use oss.New to create Client instance.
  18. //
  19. type (
  20. // Client OSS client
  21. Client struct {
  22. Config *Config // OSS client configuration
  23. Conn *Conn // Send HTTP request
  24. HTTPClient *http.Client //http.Client to use - if nil will make its own
  25. }
  26. // ClientOption client option such as UseCname, Timeout, SecurityToken.
  27. ClientOption func(*Client)
  28. )
  29. // New creates a new client.
  30. //
  31. // endpoint the OSS datacenter endpoint such as http://oss-cn-hangzhou.aliyuncs.com .
  32. // accessKeyId access key Id.
  33. // accessKeySecret access key secret.
  34. //
  35. // Client creates the new client instance, the returned value is valid when error is nil.
  36. // error it's nil if no error, otherwise it's an error object.
  37. //
  38. func New(endpoint, accessKeyID, accessKeySecret string, options ...ClientOption) (*Client, error) {
  39. // Configuration
  40. config := getDefaultOssConfig()
  41. config.Endpoint = endpoint
  42. config.AccessKeyID = accessKeyID
  43. config.AccessKeySecret = accessKeySecret
  44. // URL parse
  45. url := &urlMaker{}
  46. url.Init(config.Endpoint, config.IsCname, config.IsUseProxy)
  47. // HTTP connect
  48. conn := &Conn{config: config, url: url}
  49. // OSS client
  50. client := &Client{
  51. Config: config,
  52. Conn: conn,
  53. }
  54. // Client options parse
  55. for _, option := range options {
  56. option(client)
  57. }
  58. // Create HTTP connection
  59. err := conn.init(config, url, client.HTTPClient)
  60. return client, err
  61. }
  62. // Bucket gets the bucket instance.
  63. //
  64. // bucketName the bucket name.
  65. // Bucket the bucket object, when error is nil.
  66. //
  67. // error it's nil if no error, otherwise it's an error object.
  68. //
  69. func (client Client) Bucket(bucketName string) (*Bucket, error) {
  70. return &Bucket{
  71. client,
  72. bucketName,
  73. }, nil
  74. }
  75. // CreateBucket creates a bucket.
  76. //
  77. // bucketName the bucket name, it's globably unique and immutable. The bucket name can only consist of lowercase letters, numbers and dash ('-').
  78. // It must start with lowercase letter or number and the length can only be between 3 and 255.
  79. // options options for creating the bucket, with optional ACL. The ACL could be ACLPrivate, ACLPublicRead, and ACLPublicReadWrite. By default it's ACLPrivate.
  80. // It could also be specified with StorageClass option, which supports StorageStandard, StorageIA(infrequent access), StorageArchive.
  81. //
  82. // error it's nil if no error, otherwise it's an error object.
  83. //
  84. func (client Client) CreateBucket(bucketName string, options ...Option) error {
  85. headers := make(map[string]string)
  86. handleOptions(headers, options)
  87. buffer := new(bytes.Buffer)
  88. isOptSet, val, _ := isOptionSet(options, storageClass)
  89. if isOptSet {
  90. cbConfig := createBucketConfiguration{StorageClass: val.(StorageClassType)}
  91. bs, err := xml.Marshal(cbConfig)
  92. if err != nil {
  93. return err
  94. }
  95. buffer.Write(bs)
  96. contentType := http.DetectContentType(buffer.Bytes())
  97. headers[HTTPHeaderContentType] = contentType
  98. }
  99. params := map[string]interface{}{}
  100. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  101. if err != nil {
  102. return err
  103. }
  104. defer resp.Body.Close()
  105. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  106. }
  107. // ListBuckets lists buckets of the current account under the given endpoint, with optional filters.
  108. //
  109. // options specifies the filters such as Prefix, Marker and MaxKeys. Prefix is the bucket name's prefix filter.
  110. // And marker makes sure the returned buckets' name are greater than it in lexicographic order.
  111. // Maxkeys limits the max keys to return, and by default it's 100 and up to 1000.
  112. // For the common usage scenario, please check out list_bucket.go in the sample.
  113. // ListBucketsResponse the response object if error is nil.
  114. //
  115. // error it's nil if no error, otherwise it's an error object.
  116. //
  117. func (client Client) ListBuckets(options ...Option) (ListBucketsResult, error) {
  118. var out ListBucketsResult
  119. params, err := getRawParams(options)
  120. if err != nil {
  121. return out, err
  122. }
  123. resp, err := client.do("GET", "", params, nil, nil, options...)
  124. if err != nil {
  125. return out, err
  126. }
  127. defer resp.Body.Close()
  128. err = xmlUnmarshal(resp.Body, &out)
  129. return out, err
  130. }
  131. // IsBucketExist checks if the bucket exists
  132. //
  133. // bucketName the bucket name.
  134. //
  135. // bool true if it exists, and it's only valid when error is nil.
  136. // error it's nil if no error, otherwise it's an error object.
  137. //
  138. func (client Client) IsBucketExist(bucketName string) (bool, error) {
  139. listRes, err := client.ListBuckets(Prefix(bucketName), MaxKeys(1))
  140. if err != nil {
  141. return false, err
  142. }
  143. if len(listRes.Buckets) == 1 && listRes.Buckets[0].Name == bucketName {
  144. return true, nil
  145. }
  146. return false, nil
  147. }
  148. // DeleteBucket deletes the bucket. Only empty bucket can be deleted (no object and parts).
  149. //
  150. // bucketName the bucket name.
  151. //
  152. // error it's nil if no error, otherwise it's an error object.
  153. //
  154. func (client Client) DeleteBucket(bucketName string) error {
  155. params := map[string]interface{}{}
  156. resp, err := client.do("DELETE", bucketName, params, nil, nil)
  157. if err != nil {
  158. return err
  159. }
  160. defer resp.Body.Close()
  161. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  162. }
  163. // GetBucketLocation gets the bucket location.
  164. //
  165. // Checks out the following link for more information :
  166. // https://help.aliyun.com/document_detail/oss/user_guide/oss_concept/endpoint.html
  167. //
  168. // bucketName the bucket name
  169. //
  170. // string bucket's datacenter location
  171. // error it's nil if no error, otherwise it's an error object.
  172. //
  173. func (client Client) GetBucketLocation(bucketName string) (string, error) {
  174. params := map[string]interface{}{}
  175. params["location"] = nil
  176. resp, err := client.do("GET", bucketName, params, nil, nil)
  177. if err != nil {
  178. return "", err
  179. }
  180. defer resp.Body.Close()
  181. var LocationConstraint string
  182. err = xmlUnmarshal(resp.Body, &LocationConstraint)
  183. return LocationConstraint, err
  184. }
  185. // SetBucketACL sets bucket's ACL.
  186. //
  187. // bucketName the bucket name
  188. // bucketAcl the bucket ACL: ACLPrivate, ACLPublicRead and ACLPublicReadWrite.
  189. //
  190. // error it's nil if no error, otherwise it's an error object.
  191. //
  192. func (client Client) SetBucketACL(bucketName string, bucketACL ACLType) error {
  193. headers := map[string]string{HTTPHeaderOssACL: string(bucketACL)}
  194. params := map[string]interface{}{}
  195. params["acl"] = nil
  196. resp, err := client.do("PUT", bucketName, params, headers, nil)
  197. if err != nil {
  198. return err
  199. }
  200. defer resp.Body.Close()
  201. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  202. }
  203. // GetBucketACL gets the bucket ACL.
  204. //
  205. // bucketName the bucket name.
  206. //
  207. // GetBucketAclResponse the result object, and it's only valid when error is nil.
  208. // error it's nil if no error, otherwise it's an error object.
  209. //
  210. func (client Client) GetBucketACL(bucketName string) (GetBucketACLResult, error) {
  211. var out GetBucketACLResult
  212. params := map[string]interface{}{}
  213. params["acl"] = nil
  214. resp, err := client.do("GET", bucketName, params, nil, nil)
  215. if err != nil {
  216. return out, err
  217. }
  218. defer resp.Body.Close()
  219. err = xmlUnmarshal(resp.Body, &out)
  220. return out, err
  221. }
  222. // SetBucketLifecycle sets the bucket's lifecycle.
  223. //
  224. // For more information, checks out following link:
  225. // https://help.aliyun.com/document_detail/oss/user_guide/manage_object/object_lifecycle.html
  226. //
  227. // bucketName the bucket name.
  228. // rules the lifecycle rules. There're two kind of rules: absolute time expiration and relative time expiration in days and day/month/year respectively.
  229. // Check out sample/bucket_lifecycle.go for more details.
  230. //
  231. // error it's nil if no error, otherwise it's an error object.
  232. //
  233. func (client Client) SetBucketLifecycle(bucketName string, rules []LifecycleRule) error {
  234. err := verifyLifecycleRules(rules)
  235. if err != nil {
  236. return err
  237. }
  238. lifecycleCfg := LifecycleConfiguration{Rules: rules}
  239. bs, err := xml.Marshal(lifecycleCfg)
  240. if err != nil {
  241. return err
  242. }
  243. buffer := new(bytes.Buffer)
  244. buffer.Write(bs)
  245. contentType := http.DetectContentType(buffer.Bytes())
  246. headers := map[string]string{}
  247. headers[HTTPHeaderContentType] = contentType
  248. params := map[string]interface{}{}
  249. params["lifecycle"] = nil
  250. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  251. if err != nil {
  252. return err
  253. }
  254. defer resp.Body.Close()
  255. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  256. }
  257. // DeleteBucketLifecycle deletes the bucket's lifecycle.
  258. //
  259. //
  260. // bucketName the bucket name.
  261. //
  262. // error it's nil if no error, otherwise it's an error object.
  263. //
  264. func (client Client) DeleteBucketLifecycle(bucketName string) error {
  265. params := map[string]interface{}{}
  266. params["lifecycle"] = nil
  267. resp, err := client.do("DELETE", bucketName, params, nil, nil)
  268. if err != nil {
  269. return err
  270. }
  271. defer resp.Body.Close()
  272. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  273. }
  274. // GetBucketLifecycle gets the bucket's lifecycle settings.
  275. //
  276. // bucketName the bucket name.
  277. //
  278. // GetBucketLifecycleResponse the result object upon successful request. It's only valid when error is nil.
  279. // error it's nil if no error, otherwise it's an error object.
  280. //
  281. func (client Client) GetBucketLifecycle(bucketName string) (GetBucketLifecycleResult, error) {
  282. var out GetBucketLifecycleResult
  283. params := map[string]interface{}{}
  284. params["lifecycle"] = nil
  285. resp, err := client.do("GET", bucketName, params, nil, nil)
  286. if err != nil {
  287. return out, err
  288. }
  289. defer resp.Body.Close()
  290. err = xmlUnmarshal(resp.Body, &out)
  291. return out, err
  292. }
  293. // SetBucketReferer sets the bucket's referer whitelist and the flag if allowing empty referrer.
  294. //
  295. // 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
  296. // the allowing empty referrer flag. Note that this applies to requests from webbrowser only.
  297. // For example, for a bucket os-example and its referrer http://www.aliyun.com, all requests from this URL could access the bucket.
  298. // For more information, please check out this link :
  299. // https://help.aliyun.com/document_detail/oss/user_guide/security_management/referer.html
  300. //
  301. // bucketName the bucket name.
  302. // referers the referrer white list. A bucket could have a referrer list and each referrer supports one '*' and multiple '?' as wildcards.
  303. // The sample could be found in sample/bucket_referer.go
  304. // allowEmptyReferer the flag of allowing empty referrer. By default it's true.
  305. //
  306. // error it's nil if no error, otherwise it's an error object.
  307. //
  308. func (client Client) SetBucketReferer(bucketName string, referers []string, allowEmptyReferer bool) error {
  309. rxml := RefererXML{}
  310. rxml.AllowEmptyReferer = allowEmptyReferer
  311. if referers == nil {
  312. rxml.RefererList = append(rxml.RefererList, "")
  313. } else {
  314. for _, referer := range referers {
  315. rxml.RefererList = append(rxml.RefererList, referer)
  316. }
  317. }
  318. bs, err := xml.Marshal(rxml)
  319. if err != nil {
  320. return err
  321. }
  322. buffer := new(bytes.Buffer)
  323. buffer.Write(bs)
  324. contentType := http.DetectContentType(buffer.Bytes())
  325. headers := map[string]string{}
  326. headers[HTTPHeaderContentType] = contentType
  327. params := map[string]interface{}{}
  328. params["referer"] = nil
  329. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  330. if err != nil {
  331. return err
  332. }
  333. defer resp.Body.Close()
  334. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  335. }
  336. // GetBucketReferer gets the bucket's referrer white list.
  337. //
  338. // bucketName the bucket name.
  339. //
  340. // GetBucketRefererResponse the result object upon successful request. It's only valid when error is nil.
  341. // error it's nil if no error, otherwise it's an error object.
  342. //
  343. func (client Client) GetBucketReferer(bucketName string) (GetBucketRefererResult, error) {
  344. var out GetBucketRefererResult
  345. params := map[string]interface{}{}
  346. params["referer"] = nil
  347. resp, err := client.do("GET", bucketName, params, nil, nil)
  348. if err != nil {
  349. return out, err
  350. }
  351. defer resp.Body.Close()
  352. err = xmlUnmarshal(resp.Body, &out)
  353. return out, err
  354. }
  355. // SetBucketLogging sets the bucket logging settings.
  356. //
  357. // OSS could automatically store the access log. Only the bucket owner could enable the logging.
  358. // Once enabled, OSS would save all the access log into hourly log files in a specified bucket.
  359. // For more information, please check out https://help.aliyun.com/document_detail/oss/user_guide/security_management/logging.html
  360. //
  361. // bucketName bucket name to enable the log.
  362. // targetBucket the target bucket name to store the log files.
  363. // targetPrefix the log files' prefix.
  364. //
  365. // error it's nil if no error, otherwise it's an error object.
  366. //
  367. func (client Client) SetBucketLogging(bucketName, targetBucket, targetPrefix string,
  368. isEnable bool) error {
  369. var err error
  370. var bs []byte
  371. if isEnable {
  372. lxml := LoggingXML{}
  373. lxml.LoggingEnabled.TargetBucket = targetBucket
  374. lxml.LoggingEnabled.TargetPrefix = targetPrefix
  375. bs, err = xml.Marshal(lxml)
  376. } else {
  377. lxml := loggingXMLEmpty{}
  378. bs, err = xml.Marshal(lxml)
  379. }
  380. if err != nil {
  381. return err
  382. }
  383. buffer := new(bytes.Buffer)
  384. buffer.Write(bs)
  385. contentType := http.DetectContentType(buffer.Bytes())
  386. headers := map[string]string{}
  387. headers[HTTPHeaderContentType] = contentType
  388. params := map[string]interface{}{}
  389. params["logging"] = nil
  390. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  391. if err != nil {
  392. return err
  393. }
  394. defer resp.Body.Close()
  395. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  396. }
  397. // DeleteBucketLogging deletes the logging configuration to disable the logging on the bucket.
  398. //
  399. // bucketName the bucket name to disable the logging.
  400. //
  401. // error it's nil if no error, otherwise it's an error object.
  402. //
  403. func (client Client) DeleteBucketLogging(bucketName string) error {
  404. params := map[string]interface{}{}
  405. params["logging"] = nil
  406. resp, err := client.do("DELETE", bucketName, params, nil, nil)
  407. if err != nil {
  408. return err
  409. }
  410. defer resp.Body.Close()
  411. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  412. }
  413. // GetBucketLogging gets the bucket's logging settings
  414. //
  415. // bucketName the bucket name
  416. // GetBucketLoggingResponse the result object upon successful request. It's only valid when error is nil.
  417. //
  418. // error it's nil if no error, otherwise it's an error object.
  419. //
  420. func (client Client) GetBucketLogging(bucketName string) (GetBucketLoggingResult, error) {
  421. var out GetBucketLoggingResult
  422. params := map[string]interface{}{}
  423. params["logging"] = nil
  424. resp, err := client.do("GET", bucketName, params, nil, nil)
  425. if err != nil {
  426. return out, err
  427. }
  428. defer resp.Body.Close()
  429. err = xmlUnmarshal(resp.Body, &out)
  430. return out, err
  431. }
  432. // SetBucketWebsite sets the bucket's static website's index and error page.
  433. //
  434. // 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.
  435. // For more information, please check out: https://help.aliyun.com/document_detail/oss/user_guide/static_host_website.html
  436. //
  437. // bucketName the bucket name to enable static web site.
  438. // indexDocument index page.
  439. // errorDocument error page.
  440. //
  441. // error it's nil if no error, otherwise it's an error object.
  442. //
  443. func (client Client) SetBucketWebsite(bucketName, indexDocument, errorDocument string) error {
  444. wxml := WebsiteXML{}
  445. wxml.IndexDocument.Suffix = indexDocument
  446. wxml.ErrorDocument.Key = errorDocument
  447. bs, err := xml.Marshal(wxml)
  448. if err != nil {
  449. return err
  450. }
  451. buffer := new(bytes.Buffer)
  452. buffer.Write(bs)
  453. contentType := http.DetectContentType(buffer.Bytes())
  454. headers := make(map[string]string)
  455. headers[HTTPHeaderContentType] = contentType
  456. params := map[string]interface{}{}
  457. params["website"] = nil
  458. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  459. if err != nil {
  460. return err
  461. }
  462. defer resp.Body.Close()
  463. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  464. }
  465. // SetBucketWebsiteDetail sets the bucket's static website's detail
  466. //
  467. // 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.
  468. // For more information, please check out: https://help.aliyun.com/document_detail/oss/user_guide/static_host_website.html
  469. //
  470. // bucketName the bucket name to enable static web site.
  471. //
  472. // wxml the website's detail
  473. //
  474. // error it's nil if no error, otherwise it's an error object.
  475. //
  476. func (client Client) SetBucketWebsiteDetail(bucketName string, wxml WebsiteXML, options ...Option) error {
  477. bs, err := xml.Marshal(wxml)
  478. if err != nil {
  479. return err
  480. }
  481. buffer := new(bytes.Buffer)
  482. buffer.Write(bs)
  483. contentType := http.DetectContentType(buffer.Bytes())
  484. headers := make(map[string]string)
  485. headers[HTTPHeaderContentType] = contentType
  486. params := map[string]interface{}{}
  487. params["website"] = nil
  488. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  489. if err != nil {
  490. return err
  491. }
  492. defer resp.Body.Close()
  493. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  494. }
  495. // DeleteBucketWebsite deletes the bucket's static web site settings.
  496. //
  497. // bucketName the bucket name.
  498. //
  499. // error it's nil if no error, otherwise it's an error object.
  500. //
  501. func (client Client) DeleteBucketWebsite(bucketName string) error {
  502. params := map[string]interface{}{}
  503. params["website"] = nil
  504. resp, err := client.do("DELETE", bucketName, params, nil, nil)
  505. if err != nil {
  506. return err
  507. }
  508. defer resp.Body.Close()
  509. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  510. }
  511. // GetBucketWebsite gets the bucket's default page (index page) and the error page.
  512. //
  513. // bucketName the bucket name
  514. //
  515. // GetBucketWebsiteResponse the result object upon successful request. It's only valid when error is nil.
  516. // error it's nil if no error, otherwise it's an error object.
  517. //
  518. func (client Client) GetBucketWebsite(bucketName string) (GetBucketWebsiteResult, error) {
  519. var out GetBucketWebsiteResult
  520. params := map[string]interface{}{}
  521. params["website"] = nil
  522. resp, err := client.do("GET", bucketName, params, nil, nil)
  523. if err != nil {
  524. return out, err
  525. }
  526. defer resp.Body.Close()
  527. err = xmlUnmarshal(resp.Body, &out)
  528. return out, err
  529. }
  530. // SetBucketCORS sets the bucket's CORS rules
  531. //
  532. // For more information, please check out https://help.aliyun.com/document_detail/oss/user_guide/security_management/cors.html
  533. //
  534. // bucketName the bucket name
  535. // corsRules the CORS rules to set. The related sample code is in sample/bucket_cors.go.
  536. //
  537. // error it's nil if no error, otherwise it's an error object.
  538. //
  539. func (client Client) SetBucketCORS(bucketName string, corsRules []CORSRule) error {
  540. corsxml := CORSXML{}
  541. for _, v := range corsRules {
  542. cr := CORSRule{}
  543. cr.AllowedMethod = v.AllowedMethod
  544. cr.AllowedOrigin = v.AllowedOrigin
  545. cr.AllowedHeader = v.AllowedHeader
  546. cr.ExposeHeader = v.ExposeHeader
  547. cr.MaxAgeSeconds = v.MaxAgeSeconds
  548. corsxml.CORSRules = append(corsxml.CORSRules, cr)
  549. }
  550. bs, err := xml.Marshal(corsxml)
  551. if err != nil {
  552. return err
  553. }
  554. buffer := new(bytes.Buffer)
  555. buffer.Write(bs)
  556. contentType := http.DetectContentType(buffer.Bytes())
  557. headers := map[string]string{}
  558. headers[HTTPHeaderContentType] = contentType
  559. params := map[string]interface{}{}
  560. params["cors"] = nil
  561. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  562. if err != nil {
  563. return err
  564. }
  565. defer resp.Body.Close()
  566. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  567. }
  568. // DeleteBucketCORS deletes the bucket's static website settings.
  569. //
  570. // bucketName the bucket name.
  571. //
  572. // error it's nil if no error, otherwise it's an error object.
  573. //
  574. func (client Client) DeleteBucketCORS(bucketName string) error {
  575. params := map[string]interface{}{}
  576. params["cors"] = nil
  577. resp, err := client.do("DELETE", bucketName, params, nil, nil)
  578. if err != nil {
  579. return err
  580. }
  581. defer resp.Body.Close()
  582. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  583. }
  584. // GetBucketCORS gets the bucket's CORS settings.
  585. //
  586. // bucketName the bucket name.
  587. // GetBucketCORSResult the result object upon successful request. It's only valid when error is nil.
  588. //
  589. // error it's nil if no error, otherwise it's an error object.
  590. //
  591. func (client Client) GetBucketCORS(bucketName string) (GetBucketCORSResult, error) {
  592. var out GetBucketCORSResult
  593. params := map[string]interface{}{}
  594. params["cors"] = nil
  595. resp, err := client.do("GET", bucketName, params, nil, nil)
  596. if err != nil {
  597. return out, err
  598. }
  599. defer resp.Body.Close()
  600. err = xmlUnmarshal(resp.Body, &out)
  601. return out, err
  602. }
  603. // GetBucketInfo gets the bucket information.
  604. //
  605. // bucketName the bucket name.
  606. // GetBucketInfoResult the result object upon successful request. It's only valid when error is nil.
  607. //
  608. // error it's nil if no error, otherwise it's an error object.
  609. //
  610. func (client Client) GetBucketInfo(bucketName string) (GetBucketInfoResult, error) {
  611. var out GetBucketInfoResult
  612. params := map[string]interface{}{}
  613. params["bucketInfo"] = nil
  614. resp, err := client.do("GET", bucketName, params, nil, nil)
  615. if err != nil {
  616. return out, err
  617. }
  618. defer resp.Body.Close()
  619. err = xmlUnmarshal(resp.Body, &out)
  620. // convert None to ""
  621. if err == nil {
  622. if out.BucketInfo.SseRule.KMSMasterKeyID == "None" {
  623. out.BucketInfo.SseRule.KMSMasterKeyID = ""
  624. }
  625. if out.BucketInfo.SseRule.SSEAlgorithm == "None" {
  626. out.BucketInfo.SseRule.SSEAlgorithm = ""
  627. }
  628. }
  629. return out, err
  630. }
  631. // SetBucketVersioning set bucket versioning:Enabled、Suspended
  632. // bucketName the bucket name.
  633. // error it's nil if no error, otherwise it's an error object.
  634. func (client Client) SetBucketVersioning(bucketName string, versioningConfig VersioningConfig, options ...Option) error {
  635. var err error
  636. var bs []byte
  637. bs, err = xml.Marshal(versioningConfig)
  638. if err != nil {
  639. return err
  640. }
  641. buffer := new(bytes.Buffer)
  642. buffer.Write(bs)
  643. contentType := http.DetectContentType(buffer.Bytes())
  644. headers := map[string]string{}
  645. headers[HTTPHeaderContentType] = contentType
  646. params := map[string]interface{}{}
  647. params["versioning"] = nil
  648. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  649. if err != nil {
  650. return err
  651. }
  652. defer resp.Body.Close()
  653. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  654. }
  655. // GetBucketVersioning get bucket versioning status:Enabled、Suspended
  656. // bucketName the bucket name.
  657. // error it's nil if no error, otherwise it's an error object.
  658. func (client Client) GetBucketVersioning(bucketName string, options ...Option) (GetBucketVersioningResult, error) {
  659. var out GetBucketVersioningResult
  660. params := map[string]interface{}{}
  661. params["versioning"] = nil
  662. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  663. if err != nil {
  664. return out, err
  665. }
  666. defer resp.Body.Close()
  667. err = xmlUnmarshal(resp.Body, &out)
  668. return out, err
  669. }
  670. // SetBucketEncryption set bucket encryption config
  671. // bucketName the bucket name.
  672. // error it's nil if no error, otherwise it's an error object.
  673. func (client Client) SetBucketEncryption(bucketName string, encryptionRule ServerEncryptionRule, options ...Option) error {
  674. var err error
  675. var bs []byte
  676. bs, err = xml.Marshal(encryptionRule)
  677. if err != nil {
  678. return err
  679. }
  680. buffer := new(bytes.Buffer)
  681. buffer.Write(bs)
  682. contentType := http.DetectContentType(buffer.Bytes())
  683. headers := map[string]string{}
  684. headers[HTTPHeaderContentType] = contentType
  685. params := map[string]interface{}{}
  686. params["encryption"] = nil
  687. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  688. if err != nil {
  689. return err
  690. }
  691. defer resp.Body.Close()
  692. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  693. }
  694. // GetBucketEncryption get bucket encryption
  695. // bucketName the bucket name.
  696. // error it's nil if no error, otherwise it's an error object.
  697. func (client Client) GetBucketEncryption(bucketName string, options ...Option) (GetBucketEncryptionResult, error) {
  698. var out GetBucketEncryptionResult
  699. params := map[string]interface{}{}
  700. params["encryption"] = nil
  701. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  702. if err != nil {
  703. return out, err
  704. }
  705. defer resp.Body.Close()
  706. err = xmlUnmarshal(resp.Body, &out)
  707. return out, err
  708. }
  709. // DeleteBucketEncryption delete bucket encryption config
  710. // bucketName the bucket name.
  711. // error it's nil if no error, otherwise it's an error bucket
  712. func (client Client) DeleteBucketEncryption(bucketName string, options ...Option) error {
  713. params := map[string]interface{}{}
  714. params["encryption"] = nil
  715. resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
  716. if err != nil {
  717. return err
  718. }
  719. defer resp.Body.Close()
  720. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  721. }
  722. //
  723. // SetBucketTagging add tagging to bucket
  724. // bucketName name of bucket
  725. // tagging tagging to be added
  726. // error nil if success, otherwise error
  727. func (client Client) SetBucketTagging(bucketName string, tagging Tagging, options ...Option) error {
  728. var err error
  729. var bs []byte
  730. bs, err = xml.Marshal(tagging)
  731. if err != nil {
  732. return err
  733. }
  734. buffer := new(bytes.Buffer)
  735. buffer.Write(bs)
  736. contentType := http.DetectContentType(buffer.Bytes())
  737. headers := map[string]string{}
  738. headers[HTTPHeaderContentType] = contentType
  739. params := map[string]interface{}{}
  740. params["tagging"] = nil
  741. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  742. if err != nil {
  743. return err
  744. }
  745. defer resp.Body.Close()
  746. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  747. }
  748. // GetBucketTagging get tagging of the bucket
  749. // bucketName name of bucket
  750. // error nil if success, otherwise error
  751. func (client Client) GetBucketTagging(bucketName string, options ...Option) (GetBucketTaggingResult, error) {
  752. var out GetBucketTaggingResult
  753. params := map[string]interface{}{}
  754. params["tagging"] = nil
  755. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  756. if err != nil {
  757. return out, err
  758. }
  759. defer resp.Body.Close()
  760. err = xmlUnmarshal(resp.Body, &out)
  761. return out, err
  762. }
  763. //
  764. // DeleteBucketTagging delete bucket tagging
  765. // bucketName name of bucket
  766. // error nil if success, otherwise error
  767. //
  768. func (client Client) DeleteBucketTagging(bucketName string, options ...Option) error {
  769. params := map[string]interface{}{}
  770. params["tagging"] = nil
  771. resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
  772. if err != nil {
  773. return err
  774. }
  775. defer resp.Body.Close()
  776. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  777. }
  778. // GetBucketStat get bucket stat
  779. // bucketName the bucket name.
  780. // error it's nil if no error, otherwise it's an error object.
  781. func (client Client) GetBucketStat(bucketName string) (GetBucketStatResult, error) {
  782. var out GetBucketStatResult
  783. params := map[string]interface{}{}
  784. params["stat"] = nil
  785. resp, err := client.do("GET", bucketName, params, nil, nil)
  786. if err != nil {
  787. return out, err
  788. }
  789. defer resp.Body.Close()
  790. err = xmlUnmarshal(resp.Body, &out)
  791. return out, err
  792. }
  793. // GetBucketPolicy API operation for Object Storage Service.
  794. //
  795. // Get the policy from the bucket.
  796. //
  797. // bucketName the bucket name.
  798. //
  799. // string return the bucket's policy, and it's only valid when error is nil.
  800. //
  801. // error it's nil if no error, otherwise it's an error object.
  802. //
  803. func (client Client) GetBucketPolicy(bucketName string, options ...Option) (string, error) {
  804. params := map[string]interface{}{}
  805. params["policy"] = nil
  806. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  807. if err != nil {
  808. return "", err
  809. }
  810. defer resp.Body.Close()
  811. body, err := ioutil.ReadAll(resp.Body)
  812. out := string(body)
  813. return out, err
  814. }
  815. // SetBucketPolicy API operation for Object Storage Service.
  816. //
  817. // Set the policy from the bucket.
  818. //
  819. // bucketName the bucket name.
  820. //
  821. // policy the bucket policy.
  822. //
  823. // error it's nil if no error, otherwise it's an error object.
  824. //
  825. func (client Client) SetBucketPolicy(bucketName string, policy string, options ...Option) error {
  826. params := map[string]interface{}{}
  827. params["policy"] = nil
  828. buffer := strings.NewReader(policy)
  829. resp, err := client.do("PUT", bucketName, params, nil, buffer, options...)
  830. if err != nil {
  831. return err
  832. }
  833. defer resp.Body.Close()
  834. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  835. }
  836. // DeleteBucketPolicy API operation for Object Storage Service.
  837. //
  838. // Deletes the policy from the bucket.
  839. //
  840. // bucketName the bucket name.
  841. //
  842. // error it's nil if no error, otherwise it's an error object.
  843. //
  844. func (client Client) DeleteBucketPolicy(bucketName string, options ...Option) error {
  845. params := map[string]interface{}{}
  846. params["policy"] = nil
  847. resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
  848. if err != nil {
  849. return err
  850. }
  851. defer resp.Body.Close()
  852. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  853. }
  854. // SetBucketRequestPayment API operation for Object Storage Service.
  855. //
  856. // Set the requestPayment of bucket
  857. //
  858. // bucketName the bucket name.
  859. //
  860. // paymentConfig the payment configuration
  861. //
  862. // error it's nil if no error, otherwise it's an error object.
  863. //
  864. func (client Client) SetBucketRequestPayment(bucketName string, paymentConfig RequestPaymentConfiguration, options ...Option) error {
  865. params := map[string]interface{}{}
  866. params["requestPayment"] = nil
  867. var bs []byte
  868. bs, err := xml.Marshal(paymentConfig)
  869. if err != nil {
  870. return err
  871. }
  872. buffer := new(bytes.Buffer)
  873. buffer.Write(bs)
  874. contentType := http.DetectContentType(buffer.Bytes())
  875. headers := map[string]string{}
  876. headers[HTTPHeaderContentType] = contentType
  877. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  878. if err != nil {
  879. return err
  880. }
  881. defer resp.Body.Close()
  882. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  883. }
  884. // GetBucketRequestPayment API operation for Object Storage Service.
  885. //
  886. // Get bucket requestPayment
  887. //
  888. // bucketName the bucket name.
  889. //
  890. // RequestPaymentConfiguration the payment configuration
  891. //
  892. // error it's nil if no error, otherwise it's an error object.
  893. //
  894. func (client Client) GetBucketRequestPayment(bucketName string, options ...Option) (RequestPaymentConfiguration, error) {
  895. var out RequestPaymentConfiguration
  896. params := map[string]interface{}{}
  897. params["requestPayment"] = nil
  898. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  899. if err != nil {
  900. return out, err
  901. }
  902. defer resp.Body.Close()
  903. err = xmlUnmarshal(resp.Body, &out)
  904. return out, err
  905. }
  906. // LimitUploadSpeed set upload bandwidth limit speed,default is 0,unlimited
  907. // upSpeed KB/s, 0 is unlimited,default is 0
  908. // error it's nil if success, otherwise failure
  909. func (client Client) LimitUploadSpeed(upSpeed int) error {
  910. if client.Config == nil {
  911. return fmt.Errorf("client config is nil")
  912. }
  913. return client.Config.LimitUploadSpeed(upSpeed)
  914. }
  915. // UseCname sets the flag of using CName. By default it's false.
  916. //
  917. // isUseCname true: the endpoint has the CName, false: the endpoint does not have cname. Default is false.
  918. //
  919. func UseCname(isUseCname bool) ClientOption {
  920. return func(client *Client) {
  921. client.Config.IsCname = isUseCname
  922. client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
  923. }
  924. }
  925. // Timeout sets the HTTP timeout in seconds.
  926. //
  927. // connectTimeoutSec HTTP timeout in seconds. Default is 10 seconds. 0 means infinite (not recommended)
  928. // readWriteTimeout HTTP read or write's timeout in seconds. Default is 20 seconds. 0 means infinite.
  929. //
  930. func Timeout(connectTimeoutSec, readWriteTimeout int64) ClientOption {
  931. return func(client *Client) {
  932. client.Config.HTTPTimeout.ConnectTimeout =
  933. time.Second * time.Duration(connectTimeoutSec)
  934. client.Config.HTTPTimeout.ReadWriteTimeout =
  935. time.Second * time.Duration(readWriteTimeout)
  936. client.Config.HTTPTimeout.HeaderTimeout =
  937. time.Second * time.Duration(readWriteTimeout)
  938. client.Config.HTTPTimeout.IdleConnTimeout =
  939. time.Second * time.Duration(readWriteTimeout)
  940. client.Config.HTTPTimeout.LongTimeout =
  941. time.Second * time.Duration(readWriteTimeout*10)
  942. }
  943. }
  944. // SecurityToken sets the temporary user's SecurityToken.
  945. //
  946. // token STS token
  947. //
  948. func SecurityToken(token string) ClientOption {
  949. return func(client *Client) {
  950. client.Config.SecurityToken = strings.TrimSpace(token)
  951. }
  952. }
  953. // EnableMD5 enables MD5 validation.
  954. //
  955. // isEnableMD5 true: enable MD5 validation; false: disable MD5 validation.
  956. //
  957. func EnableMD5(isEnableMD5 bool) ClientOption {
  958. return func(client *Client) {
  959. client.Config.IsEnableMD5 = isEnableMD5
  960. }
  961. }
  962. // MD5ThresholdCalcInMemory sets the memory usage threshold for computing the MD5, default is 16MB.
  963. //
  964. // threshold the memory threshold in bytes. When the uploaded content is more than 16MB, the temp file is used for computing the MD5.
  965. //
  966. func MD5ThresholdCalcInMemory(threshold int64) ClientOption {
  967. return func(client *Client) {
  968. client.Config.MD5Threshold = threshold
  969. }
  970. }
  971. // EnableCRC enables the CRC checksum. Default is true.
  972. //
  973. // isEnableCRC true: enable CRC checksum; false: disable the CRC checksum.
  974. //
  975. func EnableCRC(isEnableCRC bool) ClientOption {
  976. return func(client *Client) {
  977. client.Config.IsEnableCRC = isEnableCRC
  978. }
  979. }
  980. // UserAgent specifies UserAgent. The default is aliyun-sdk-go/1.2.0 (windows/-/amd64;go1.5.2).
  981. //
  982. // userAgent the user agent string.
  983. //
  984. func UserAgent(userAgent string) ClientOption {
  985. return func(client *Client) {
  986. client.Config.UserAgent = userAgent
  987. }
  988. }
  989. // Proxy sets the proxy (optional). The default is not using proxy.
  990. //
  991. // proxyHost the proxy host in the format "host:port". For example, proxy.com:80 .
  992. //
  993. func Proxy(proxyHost string) ClientOption {
  994. return func(client *Client) {
  995. client.Config.IsUseProxy = true
  996. client.Config.ProxyHost = proxyHost
  997. client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
  998. }
  999. }
  1000. // AuthProxy sets the proxy information with user name and password.
  1001. //
  1002. // proxyHost the proxy host in the format "host:port". For example, proxy.com:80 .
  1003. // proxyUser the proxy user name.
  1004. // proxyPassword the proxy password.
  1005. //
  1006. func AuthProxy(proxyHost, proxyUser, proxyPassword string) ClientOption {
  1007. return func(client *Client) {
  1008. client.Config.IsUseProxy = true
  1009. client.Config.ProxyHost = proxyHost
  1010. client.Config.IsAuthProxy = true
  1011. client.Config.ProxyUser = proxyUser
  1012. client.Config.ProxyPassword = proxyPassword
  1013. client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
  1014. }
  1015. }
  1016. //
  1017. // HTTPClient sets the http.Client in use to the one passed in
  1018. //
  1019. func HTTPClient(HTTPClient *http.Client) ClientOption {
  1020. return func(client *Client) {
  1021. client.HTTPClient = HTTPClient
  1022. }
  1023. }
  1024. //
  1025. // SetLogLevel sets the oss sdk log level
  1026. //
  1027. func SetLogLevel(LogLevel int) ClientOption {
  1028. return func(client *Client) {
  1029. client.Config.LogLevel = LogLevel
  1030. }
  1031. }
  1032. //
  1033. // SetLogger sets the oss sdk logger
  1034. //
  1035. func SetLogger(Logger *log.Logger) ClientOption {
  1036. return func(client *Client) {
  1037. client.Config.Logger = Logger
  1038. }
  1039. }
  1040. //
  1041. // SetAKInterface sets funciton for get the user's ak
  1042. //
  1043. func SetAKInterface(akIf AKInterface) ClientOption {
  1044. return func(client *Client) {
  1045. client.Config.UserAKInf = akIf
  1046. }
  1047. }
  1048. // Private
  1049. func (client Client) do(method, bucketName string, params map[string]interface{},
  1050. headers map[string]string, data io.Reader, options ...Option) (*Response, error) {
  1051. resp, err := client.Conn.Do(method, bucketName, "", params,
  1052. headers, data, 0, nil)
  1053. // get response header
  1054. respHeader, _ := findOption(options, responseHeader, nil)
  1055. if respHeader != nil {
  1056. pRespHeader := respHeader.(*http.Header)
  1057. *pRespHeader = resp.Headers
  1058. }
  1059. return resp, err
  1060. }