client.go 36 KB

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