client.go 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563
  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"
  12. "net/http"
  13. "strings"
  14. "time"
  15. )
  16. // 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).
  17. // Object related operations are done by Bucket class.
  18. // Users use oss.New to create Client instance.
  19. //
  20. type (
  21. // Client OSS client
  22. Client struct {
  23. Config *Config // OSS client configuration
  24. Conn *Conn // Send HTTP request
  25. HTTPClient *http.Client //http.Client to use - if nil will make its own
  26. }
  27. // ClientOption client option such as UseCname, Timeout, SecurityToken.
  28. ClientOption func(*Client)
  29. )
  30. // New creates a new client.
  31. //
  32. // endpoint the OSS datacenter endpoint such as http://oss-cn-hangzhou.aliyuncs.com .
  33. // accessKeyId access key Id.
  34. // accessKeySecret access key secret.
  35. //
  36. // Client creates the new client instance, the returned value is valid when error is nil.
  37. // error it's nil if no error, otherwise it's an error object.
  38. //
  39. func New(endpoint, accessKeyID, accessKeySecret string, options ...ClientOption) (*Client, error) {
  40. // Configuration
  41. config := getDefaultOssConfig()
  42. config.Endpoint = endpoint
  43. config.AccessKeyID = accessKeyID
  44. config.AccessKeySecret = accessKeySecret
  45. // URL parse
  46. url := &urlMaker{}
  47. err := url.Init(config.Endpoint, config.IsCname, config.IsUseProxy)
  48. if err != nil {
  49. return nil, err
  50. }
  51. // HTTP connect
  52. conn := &Conn{config: config, url: url}
  53. // OSS client
  54. client := &Client{
  55. Config: config,
  56. Conn: conn,
  57. }
  58. // Client options parse
  59. for _, option := range options {
  60. option(client)
  61. }
  62. if config.AuthVersion != AuthV1 && config.AuthVersion != AuthV2 {
  63. return nil, fmt.Errorf("Init client Error, invalid Auth version: %v", config.AuthVersion)
  64. }
  65. // Create HTTP connection
  66. err = conn.init(config, url, client.HTTPClient)
  67. return client, err
  68. }
  69. // Bucket gets the bucket instance.
  70. //
  71. // bucketName the bucket name.
  72. // Bucket the bucket object, when error is nil.
  73. //
  74. // error it's nil if no error, otherwise it's an error object.
  75. //
  76. func (client Client) Bucket(bucketName string) (*Bucket, error) {
  77. err := CheckBucketName(bucketName)
  78. if err != nil {
  79. return nil, err
  80. }
  81. return &Bucket{
  82. client,
  83. bucketName,
  84. }, nil
  85. }
  86. // CreateBucket creates a bucket.
  87. //
  88. // bucketName the bucket name, it's globably unique and immutable. The bucket name can only consist of lowercase letters, numbers and dash ('-').
  89. // It must start with lowercase letter or number and the length can only be between 3 and 255.
  90. // options options for creating the bucket, with optional ACL. The ACL could be ACLPrivate, ACLPublicRead, and ACLPublicReadWrite. By default it's ACLPrivate.
  91. // It could also be specified with StorageClass option, which supports StorageStandard, StorageIA(infrequent access), StorageArchive.
  92. //
  93. // error it's nil if no error, otherwise it's an error object.
  94. //
  95. func (client Client) CreateBucket(bucketName string, options ...Option) error {
  96. headers := make(map[string]string)
  97. handleOptions(headers, options)
  98. buffer := new(bytes.Buffer)
  99. var cbConfig createBucketConfiguration
  100. cbConfig.StorageClass = StorageStandard
  101. isStorageSet, valStroage, _ := IsOptionSet(options, storageClass)
  102. isRedundancySet, valRedundancy, _ := IsOptionSet(options, redundancyType)
  103. if isStorageSet {
  104. cbConfig.StorageClass = valStroage.(StorageClassType)
  105. }
  106. if isRedundancySet {
  107. cbConfig.DataRedundancyType = valRedundancy.(DataRedundancyType)
  108. }
  109. bs, err := xml.Marshal(cbConfig)
  110. if err != nil {
  111. return err
  112. }
  113. buffer.Write(bs)
  114. contentType := http.DetectContentType(buffer.Bytes())
  115. headers[HTTPHeaderContentType] = contentType
  116. params := map[string]interface{}{}
  117. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  118. if err != nil {
  119. return err
  120. }
  121. defer resp.Body.Close()
  122. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  123. }
  124. // ListBuckets lists buckets of the current account under the given endpoint, with optional filters.
  125. //
  126. // options specifies the filters such as Prefix, Marker and MaxKeys. Prefix is the bucket name's prefix filter.
  127. // And marker makes sure the returned buckets' name are greater than it in lexicographic order.
  128. // Maxkeys limits the max keys to return, and by default it's 100 and up to 1000.
  129. // For the common usage scenario, please check out list_bucket.go in the sample.
  130. // ListBucketsResponse the response object if error is nil.
  131. //
  132. // error it's nil if no error, otherwise it's an error object.
  133. //
  134. func (client Client) ListBuckets(options ...Option) (ListBucketsResult, error) {
  135. var out ListBucketsResult
  136. params, err := GetRawParams(options)
  137. if err != nil {
  138. return out, err
  139. }
  140. resp, err := client.do("GET", "", params, nil, nil, options...)
  141. if err != nil {
  142. return out, err
  143. }
  144. defer resp.Body.Close()
  145. err = xmlUnmarshal(resp.Body, &out)
  146. return out, err
  147. }
  148. // IsBucketExist checks if the bucket exists
  149. //
  150. // bucketName the bucket name.
  151. //
  152. // bool true if it exists, and it's only valid when error is nil.
  153. // error it's nil if no error, otherwise it's an error object.
  154. //
  155. func (client Client) IsBucketExist(bucketName string) (bool, error) {
  156. listRes, err := client.ListBuckets(Prefix(bucketName), MaxKeys(1))
  157. if err != nil {
  158. return false, err
  159. }
  160. if len(listRes.Buckets) == 1 && listRes.Buckets[0].Name == bucketName {
  161. return true, nil
  162. }
  163. return false, nil
  164. }
  165. // DeleteBucket deletes the bucket. Only empty bucket can be deleted (no object and parts).
  166. //
  167. // bucketName the bucket name.
  168. //
  169. // error it's nil if no error, otherwise it's an error object.
  170. //
  171. func (client Client) DeleteBucket(bucketName string, options ...Option) error {
  172. params := map[string]interface{}{}
  173. resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
  174. if err != nil {
  175. return err
  176. }
  177. defer resp.Body.Close()
  178. return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
  179. }
  180. // GetBucketLocation gets the bucket location.
  181. //
  182. // Checks out the following link for more information :
  183. // https://help.aliyun.com/document_detail/oss/user_guide/oss_concept/endpoint.html
  184. //
  185. // bucketName the bucket name
  186. //
  187. // string bucket's datacenter location
  188. // error it's nil if no error, otherwise it's an error object.
  189. //
  190. func (client Client) GetBucketLocation(bucketName string) (string, error) {
  191. params := map[string]interface{}{}
  192. params["location"] = nil
  193. resp, err := client.do("GET", bucketName, params, nil, nil)
  194. if err != nil {
  195. return "", err
  196. }
  197. defer resp.Body.Close()
  198. var LocationConstraint string
  199. err = xmlUnmarshal(resp.Body, &LocationConstraint)
  200. return LocationConstraint, err
  201. }
  202. // SetBucketACL sets bucket's ACL.
  203. //
  204. // bucketName the bucket name
  205. // bucketAcl the bucket ACL: ACLPrivate, ACLPublicRead and ACLPublicReadWrite.
  206. //
  207. // error it's nil if no error, otherwise it's an error object.
  208. //
  209. func (client Client) SetBucketACL(bucketName string, bucketACL ACLType) error {
  210. headers := map[string]string{HTTPHeaderOssACL: string(bucketACL)}
  211. params := map[string]interface{}{}
  212. params["acl"] = nil
  213. resp, err := client.do("PUT", bucketName, params, headers, nil)
  214. if err != nil {
  215. return err
  216. }
  217. defer resp.Body.Close()
  218. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  219. }
  220. // GetBucketACL gets the bucket ACL.
  221. //
  222. // bucketName the bucket name.
  223. //
  224. // GetBucketAclResponse the result object, and it's only valid when error is nil.
  225. // error it's nil if no error, otherwise it's an error object.
  226. //
  227. func (client Client) GetBucketACL(bucketName string) (GetBucketACLResult, error) {
  228. var out GetBucketACLResult
  229. params := map[string]interface{}{}
  230. params["acl"] = nil
  231. resp, err := client.do("GET", bucketName, params, nil, nil)
  232. if err != nil {
  233. return out, err
  234. }
  235. defer resp.Body.Close()
  236. err = xmlUnmarshal(resp.Body, &out)
  237. return out, err
  238. }
  239. // SetBucketLifecycle sets the bucket's lifecycle.
  240. //
  241. // For more information, checks out following link:
  242. // https://help.aliyun.com/document_detail/oss/user_guide/manage_object/object_lifecycle.html
  243. //
  244. // bucketName the bucket name.
  245. // rules the lifecycle rules. There're two kind of rules: absolute time expiration and relative time expiration in days and day/month/year respectively.
  246. // Check out sample/bucket_lifecycle.go for more details.
  247. //
  248. // error it's nil if no error, otherwise it's an error object.
  249. //
  250. func (client Client) SetBucketLifecycle(bucketName string, rules []LifecycleRule) error {
  251. err := verifyLifecycleRules(rules)
  252. if err != nil {
  253. return err
  254. }
  255. lifecycleCfg := LifecycleConfiguration{Rules: rules}
  256. bs, err := xml.Marshal(lifecycleCfg)
  257. if err != nil {
  258. return err
  259. }
  260. buffer := new(bytes.Buffer)
  261. buffer.Write(bs)
  262. contentType := http.DetectContentType(buffer.Bytes())
  263. headers := map[string]string{}
  264. headers[HTTPHeaderContentType] = contentType
  265. params := map[string]interface{}{}
  266. params["lifecycle"] = nil
  267. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  268. if err != nil {
  269. return err
  270. }
  271. defer resp.Body.Close()
  272. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  273. }
  274. // DeleteBucketLifecycle deletes the bucket's lifecycle.
  275. //
  276. //
  277. // bucketName the bucket name.
  278. //
  279. // error it's nil if no error, otherwise it's an error object.
  280. //
  281. func (client Client) DeleteBucketLifecycle(bucketName string) error {
  282. params := map[string]interface{}{}
  283. params["lifecycle"] = nil
  284. resp, err := client.do("DELETE", bucketName, params, nil, nil)
  285. if err != nil {
  286. return err
  287. }
  288. defer resp.Body.Close()
  289. return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
  290. }
  291. // GetBucketLifecycle gets the bucket's lifecycle settings.
  292. //
  293. // bucketName the bucket name.
  294. //
  295. // GetBucketLifecycleResponse the result object upon successful request. It's only valid when error is nil.
  296. // error it's nil if no error, otherwise it's an error object.
  297. //
  298. func (client Client) GetBucketLifecycle(bucketName string) (GetBucketLifecycleResult, error) {
  299. var out GetBucketLifecycleResult
  300. params := map[string]interface{}{}
  301. params["lifecycle"] = nil
  302. resp, err := client.do("GET", bucketName, params, nil, nil)
  303. if err != nil {
  304. return out, err
  305. }
  306. defer resp.Body.Close()
  307. err = xmlUnmarshal(resp.Body, &out)
  308. return out, err
  309. }
  310. // SetBucketReferer sets the bucket's referer whitelist and the flag if allowing empty referrer.
  311. //
  312. // 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
  313. // the allowing empty referrer flag. Note that this applies to requests from webbrowser only.
  314. // For example, for a bucket os-example and its referrer http://www.aliyun.com, all requests from this URL could access the bucket.
  315. // For more information, please check out this link :
  316. // https://help.aliyun.com/document_detail/oss/user_guide/security_management/referer.html
  317. //
  318. // bucketName the bucket name.
  319. // referers the referrer white list. A bucket could have a referrer list and each referrer supports one '*' and multiple '?' as wildcards.
  320. // The sample could be found in sample/bucket_referer.go
  321. // allowEmptyReferer the flag of allowing empty referrer. By default it's true.
  322. //
  323. // error it's nil if no error, otherwise it's an error object.
  324. //
  325. func (client Client) SetBucketReferer(bucketName string, referers []string, allowEmptyReferer bool) error {
  326. rxml := RefererXML{}
  327. rxml.AllowEmptyReferer = allowEmptyReferer
  328. if referers == nil {
  329. rxml.RefererList = append(rxml.RefererList, "")
  330. } else {
  331. for _, referer := range referers {
  332. rxml.RefererList = append(rxml.RefererList, referer)
  333. }
  334. }
  335. bs, err := xml.Marshal(rxml)
  336. if err != nil {
  337. return err
  338. }
  339. buffer := new(bytes.Buffer)
  340. buffer.Write(bs)
  341. contentType := http.DetectContentType(buffer.Bytes())
  342. headers := map[string]string{}
  343. headers[HTTPHeaderContentType] = contentType
  344. params := map[string]interface{}{}
  345. params["referer"] = nil
  346. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  347. if err != nil {
  348. return err
  349. }
  350. defer resp.Body.Close()
  351. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  352. }
  353. // GetBucketReferer gets the bucket's referrer white list.
  354. //
  355. // bucketName the bucket name.
  356. //
  357. // GetBucketRefererResponse the result object upon successful request. It's only valid when error is nil.
  358. // error it's nil if no error, otherwise it's an error object.
  359. //
  360. func (client Client) GetBucketReferer(bucketName string) (GetBucketRefererResult, error) {
  361. var out GetBucketRefererResult
  362. params := map[string]interface{}{}
  363. params["referer"] = nil
  364. resp, err := client.do("GET", bucketName, params, nil, nil)
  365. if err != nil {
  366. return out, err
  367. }
  368. defer resp.Body.Close()
  369. err = xmlUnmarshal(resp.Body, &out)
  370. return out, err
  371. }
  372. // SetBucketLogging sets the bucket logging settings.
  373. //
  374. // OSS could automatically store the access log. Only the bucket owner could enable the logging.
  375. // Once enabled, OSS would save all the access log into hourly log files in a specified bucket.
  376. // For more information, please check out https://help.aliyun.com/document_detail/oss/user_guide/security_management/logging.html
  377. //
  378. // bucketName bucket name to enable the log.
  379. // targetBucket the target bucket name to store the log files.
  380. // targetPrefix the log files' prefix.
  381. //
  382. // error it's nil if no error, otherwise it's an error object.
  383. //
  384. func (client Client) SetBucketLogging(bucketName, targetBucket, targetPrefix string,
  385. isEnable bool) error {
  386. var err error
  387. var bs []byte
  388. if isEnable {
  389. lxml := LoggingXML{}
  390. lxml.LoggingEnabled.TargetBucket = targetBucket
  391. lxml.LoggingEnabled.TargetPrefix = targetPrefix
  392. bs, err = xml.Marshal(lxml)
  393. } else {
  394. lxml := loggingXMLEmpty{}
  395. bs, err = xml.Marshal(lxml)
  396. }
  397. if err != nil {
  398. return err
  399. }
  400. buffer := new(bytes.Buffer)
  401. buffer.Write(bs)
  402. contentType := http.DetectContentType(buffer.Bytes())
  403. headers := map[string]string{}
  404. headers[HTTPHeaderContentType] = contentType
  405. params := map[string]interface{}{}
  406. params["logging"] = nil
  407. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  408. if err != nil {
  409. return err
  410. }
  411. defer resp.Body.Close()
  412. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  413. }
  414. // DeleteBucketLogging deletes the logging configuration to disable the logging on the bucket.
  415. //
  416. // bucketName the bucket name to disable the logging.
  417. //
  418. // error it's nil if no error, otherwise it's an error object.
  419. //
  420. func (client Client) DeleteBucketLogging(bucketName string) error {
  421. params := map[string]interface{}{}
  422. params["logging"] = nil
  423. resp, err := client.do("DELETE", bucketName, params, nil, nil)
  424. if err != nil {
  425. return err
  426. }
  427. defer resp.Body.Close()
  428. return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
  429. }
  430. // GetBucketLogging gets the bucket's logging settings
  431. //
  432. // bucketName the bucket name
  433. // GetBucketLoggingResponse the result object upon successful request. It's only valid when error is nil.
  434. //
  435. // error it's nil if no error, otherwise it's an error object.
  436. //
  437. func (client Client) GetBucketLogging(bucketName string) (GetBucketLoggingResult, error) {
  438. var out GetBucketLoggingResult
  439. params := map[string]interface{}{}
  440. params["logging"] = nil
  441. resp, err := client.do("GET", bucketName, params, nil, nil)
  442. if err != nil {
  443. return out, err
  444. }
  445. defer resp.Body.Close()
  446. err = xmlUnmarshal(resp.Body, &out)
  447. return out, err
  448. }
  449. // SetBucketWebsite sets the bucket's static website's index and error page.
  450. //
  451. // 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.
  452. // For more information, please check out: https://help.aliyun.com/document_detail/oss/user_guide/static_host_website.html
  453. //
  454. // bucketName the bucket name to enable static web site.
  455. // indexDocument index page.
  456. // errorDocument error page.
  457. //
  458. // error it's nil if no error, otherwise it's an error object.
  459. //
  460. func (client Client) SetBucketWebsite(bucketName, indexDocument, errorDocument string) error {
  461. wxml := WebsiteXML{}
  462. wxml.IndexDocument.Suffix = indexDocument
  463. wxml.ErrorDocument.Key = errorDocument
  464. bs, err := xml.Marshal(wxml)
  465. if err != nil {
  466. return err
  467. }
  468. buffer := new(bytes.Buffer)
  469. buffer.Write(bs)
  470. contentType := http.DetectContentType(buffer.Bytes())
  471. headers := make(map[string]string)
  472. headers[HTTPHeaderContentType] = contentType
  473. params := map[string]interface{}{}
  474. params["website"] = nil
  475. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  476. if err != nil {
  477. return err
  478. }
  479. defer resp.Body.Close()
  480. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  481. }
  482. // SetBucketWebsiteDetail sets the bucket's static website's detail
  483. //
  484. // 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.
  485. // For more information, please check out: https://help.aliyun.com/document_detail/oss/user_guide/static_host_website.html
  486. //
  487. // bucketName the bucket name to enable static web site.
  488. //
  489. // wxml the website's detail
  490. //
  491. // error it's nil if no error, otherwise it's an error object.
  492. //
  493. func (client Client) SetBucketWebsiteDetail(bucketName string, wxml WebsiteXML, options ...Option) error {
  494. bs, err := xml.Marshal(wxml)
  495. if err != nil {
  496. return err
  497. }
  498. buffer := new(bytes.Buffer)
  499. buffer.Write(bs)
  500. contentType := http.DetectContentType(buffer.Bytes())
  501. headers := make(map[string]string)
  502. headers[HTTPHeaderContentType] = contentType
  503. params := map[string]interface{}{}
  504. params["website"] = nil
  505. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  506. if err != nil {
  507. return err
  508. }
  509. defer resp.Body.Close()
  510. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  511. }
  512. // SetBucketWebsiteXml sets the bucket's static website's rule
  513. //
  514. // 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.
  515. // For more information, please check out: https://help.aliyun.com/document_detail/oss/user_guide/static_host_website.html
  516. //
  517. // bucketName the bucket name to enable static web site.
  518. //
  519. // wxml the website's detail
  520. //
  521. // error it's nil if no error, otherwise it's an error object.
  522. //
  523. func (client Client) SetBucketWebsiteXml(bucketName string, webXml string, options ...Option) error {
  524. buffer := new(bytes.Buffer)
  525. buffer.Write([]byte(webXml))
  526. contentType := http.DetectContentType(buffer.Bytes())
  527. headers := make(map[string]string)
  528. headers[HTTPHeaderContentType] = contentType
  529. params := map[string]interface{}{}
  530. params["website"] = nil
  531. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  532. if err != nil {
  533. return err
  534. }
  535. defer resp.Body.Close()
  536. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  537. }
  538. // DeleteBucketWebsite deletes the bucket's static web site settings.
  539. //
  540. // bucketName the bucket name.
  541. //
  542. // error it's nil if no error, otherwise it's an error object.
  543. //
  544. func (client Client) DeleteBucketWebsite(bucketName string) error {
  545. params := map[string]interface{}{}
  546. params["website"] = nil
  547. resp, err := client.do("DELETE", bucketName, params, nil, nil)
  548. if err != nil {
  549. return err
  550. }
  551. defer resp.Body.Close()
  552. return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
  553. }
  554. // GetBucketWebsite gets the bucket's default page (index page) and the error page.
  555. //
  556. // bucketName the bucket name
  557. //
  558. // GetBucketWebsiteResponse the result object upon successful request. It's only valid when error is nil.
  559. // error it's nil if no error, otherwise it's an error object.
  560. //
  561. func (client Client) GetBucketWebsite(bucketName string) (GetBucketWebsiteResult, error) {
  562. var out GetBucketWebsiteResult
  563. params := map[string]interface{}{}
  564. params["website"] = nil
  565. resp, err := client.do("GET", bucketName, params, nil, nil)
  566. if err != nil {
  567. return out, err
  568. }
  569. defer resp.Body.Close()
  570. err = xmlUnmarshal(resp.Body, &out)
  571. return out, err
  572. }
  573. // SetBucketCORS sets the bucket's CORS rules
  574. //
  575. // For more information, please check out https://help.aliyun.com/document_detail/oss/user_guide/security_management/cors.html
  576. //
  577. // bucketName the bucket name
  578. // corsRules the CORS rules to set. The related sample code is in sample/bucket_cors.go.
  579. //
  580. // error it's nil if no error, otherwise it's an error object.
  581. //
  582. func (client Client) SetBucketCORS(bucketName string, corsRules []CORSRule) error {
  583. corsxml := CORSXML{}
  584. for _, v := range corsRules {
  585. cr := CORSRule{}
  586. cr.AllowedMethod = v.AllowedMethod
  587. cr.AllowedOrigin = v.AllowedOrigin
  588. cr.AllowedHeader = v.AllowedHeader
  589. cr.ExposeHeader = v.ExposeHeader
  590. cr.MaxAgeSeconds = v.MaxAgeSeconds
  591. corsxml.CORSRules = append(corsxml.CORSRules, cr)
  592. }
  593. bs, err := xml.Marshal(corsxml)
  594. if err != nil {
  595. return err
  596. }
  597. buffer := new(bytes.Buffer)
  598. buffer.Write(bs)
  599. contentType := http.DetectContentType(buffer.Bytes())
  600. headers := map[string]string{}
  601. headers[HTTPHeaderContentType] = contentType
  602. params := map[string]interface{}{}
  603. params["cors"] = nil
  604. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  605. if err != nil {
  606. return err
  607. }
  608. defer resp.Body.Close()
  609. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  610. }
  611. // DeleteBucketCORS deletes the bucket's static website settings.
  612. //
  613. // bucketName the bucket name.
  614. //
  615. // error it's nil if no error, otherwise it's an error object.
  616. //
  617. func (client Client) DeleteBucketCORS(bucketName string) error {
  618. params := map[string]interface{}{}
  619. params["cors"] = nil
  620. resp, err := client.do("DELETE", bucketName, params, nil, nil)
  621. if err != nil {
  622. return err
  623. }
  624. defer resp.Body.Close()
  625. return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
  626. }
  627. // GetBucketCORS gets the bucket's CORS settings.
  628. //
  629. // bucketName the bucket name.
  630. // GetBucketCORSResult the result object upon successful request. It's only valid when error is nil.
  631. //
  632. // error it's nil if no error, otherwise it's an error object.
  633. //
  634. func (client Client) GetBucketCORS(bucketName string) (GetBucketCORSResult, error) {
  635. var out GetBucketCORSResult
  636. params := map[string]interface{}{}
  637. params["cors"] = nil
  638. resp, err := client.do("GET", bucketName, params, nil, nil)
  639. if err != nil {
  640. return out, err
  641. }
  642. defer resp.Body.Close()
  643. err = xmlUnmarshal(resp.Body, &out)
  644. return out, err
  645. }
  646. // GetBucketInfo gets the bucket information.
  647. //
  648. // bucketName the bucket name.
  649. // GetBucketInfoResult the result object upon successful request. It's only valid when error is nil.
  650. //
  651. // error it's nil if no error, otherwise it's an error object.
  652. //
  653. func (client Client) GetBucketInfo(bucketName string, options ...Option) (GetBucketInfoResult, error) {
  654. var out GetBucketInfoResult
  655. params := map[string]interface{}{}
  656. params["bucketInfo"] = nil
  657. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  658. if err != nil {
  659. return out, err
  660. }
  661. defer resp.Body.Close()
  662. err = xmlUnmarshal(resp.Body, &out)
  663. // convert None to ""
  664. if err == nil {
  665. if out.BucketInfo.SseRule.KMSMasterKeyID == "None" {
  666. out.BucketInfo.SseRule.KMSMasterKeyID = ""
  667. }
  668. if out.BucketInfo.SseRule.SSEAlgorithm == "None" {
  669. out.BucketInfo.SseRule.SSEAlgorithm = ""
  670. }
  671. if out.BucketInfo.SseRule.KMSDataEncryption == "None" {
  672. out.BucketInfo.SseRule.KMSDataEncryption = ""
  673. }
  674. }
  675. return out, err
  676. }
  677. // SetBucketVersioning set bucket versioning:Enabled、Suspended
  678. // bucketName the bucket name.
  679. // error it's nil if no error, otherwise it's an error object.
  680. func (client Client) SetBucketVersioning(bucketName string, versioningConfig VersioningConfig, options ...Option) error {
  681. var err error
  682. var bs []byte
  683. bs, err = xml.Marshal(versioningConfig)
  684. if err != nil {
  685. return err
  686. }
  687. buffer := new(bytes.Buffer)
  688. buffer.Write(bs)
  689. contentType := http.DetectContentType(buffer.Bytes())
  690. headers := map[string]string{}
  691. headers[HTTPHeaderContentType] = contentType
  692. params := map[string]interface{}{}
  693. params["versioning"] = nil
  694. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  695. if err != nil {
  696. return err
  697. }
  698. defer resp.Body.Close()
  699. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  700. }
  701. // GetBucketVersioning get bucket versioning status:Enabled、Suspended
  702. // bucketName the bucket name.
  703. // error it's nil if no error, otherwise it's an error object.
  704. func (client Client) GetBucketVersioning(bucketName string, options ...Option) (GetBucketVersioningResult, error) {
  705. var out GetBucketVersioningResult
  706. params := map[string]interface{}{}
  707. params["versioning"] = nil
  708. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  709. if err != nil {
  710. return out, err
  711. }
  712. defer resp.Body.Close()
  713. err = xmlUnmarshal(resp.Body, &out)
  714. return out, err
  715. }
  716. // SetBucketEncryption set bucket encryption config
  717. // bucketName the bucket name.
  718. // error it's nil if no error, otherwise it's an error object.
  719. func (client Client) SetBucketEncryption(bucketName string, encryptionRule ServerEncryptionRule, options ...Option) error {
  720. var err error
  721. var bs []byte
  722. bs, err = xml.Marshal(encryptionRule)
  723. if err != nil {
  724. return err
  725. }
  726. buffer := new(bytes.Buffer)
  727. buffer.Write(bs)
  728. contentType := http.DetectContentType(buffer.Bytes())
  729. headers := map[string]string{}
  730. headers[HTTPHeaderContentType] = contentType
  731. params := map[string]interface{}{}
  732. params["encryption"] = nil
  733. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  734. if err != nil {
  735. return err
  736. }
  737. defer resp.Body.Close()
  738. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  739. }
  740. // GetBucketEncryption get bucket encryption
  741. // bucketName the bucket name.
  742. // error it's nil if no error, otherwise it's an error object.
  743. func (client Client) GetBucketEncryption(bucketName string, options ...Option) (GetBucketEncryptionResult, error) {
  744. var out GetBucketEncryptionResult
  745. params := map[string]interface{}{}
  746. params["encryption"] = nil
  747. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  748. if err != nil {
  749. return out, err
  750. }
  751. defer resp.Body.Close()
  752. err = xmlUnmarshal(resp.Body, &out)
  753. return out, err
  754. }
  755. // DeleteBucketEncryption delete bucket encryption config
  756. // bucketName the bucket name.
  757. // error it's nil if no error, otherwise it's an error bucket
  758. func (client Client) DeleteBucketEncryption(bucketName string, options ...Option) error {
  759. params := map[string]interface{}{}
  760. params["encryption"] = nil
  761. resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
  762. if err != nil {
  763. return err
  764. }
  765. defer resp.Body.Close()
  766. return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
  767. }
  768. //
  769. // SetBucketTagging add tagging to bucket
  770. // bucketName name of bucket
  771. // tagging tagging to be added
  772. // error nil if success, otherwise error
  773. func (client Client) SetBucketTagging(bucketName string, tagging Tagging, options ...Option) error {
  774. var err error
  775. var bs []byte
  776. bs, err = xml.Marshal(tagging)
  777. if err != nil {
  778. return err
  779. }
  780. buffer := new(bytes.Buffer)
  781. buffer.Write(bs)
  782. contentType := http.DetectContentType(buffer.Bytes())
  783. headers := map[string]string{}
  784. headers[HTTPHeaderContentType] = contentType
  785. params := map[string]interface{}{}
  786. params["tagging"] = nil
  787. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  788. if err != nil {
  789. return err
  790. }
  791. defer resp.Body.Close()
  792. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  793. }
  794. // GetBucketTagging get tagging of the bucket
  795. // bucketName name of bucket
  796. // error nil if success, otherwise error
  797. func (client Client) GetBucketTagging(bucketName string, options ...Option) (GetBucketTaggingResult, error) {
  798. var out GetBucketTaggingResult
  799. params := map[string]interface{}{}
  800. params["tagging"] = nil
  801. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  802. if err != nil {
  803. return out, err
  804. }
  805. defer resp.Body.Close()
  806. err = xmlUnmarshal(resp.Body, &out)
  807. return out, err
  808. }
  809. //
  810. // DeleteBucketTagging delete bucket tagging
  811. // bucketName name of bucket
  812. // error nil if success, otherwise error
  813. //
  814. func (client Client) DeleteBucketTagging(bucketName string, options ...Option) error {
  815. params := map[string]interface{}{}
  816. params["tagging"] = nil
  817. resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
  818. if err != nil {
  819. return err
  820. }
  821. defer resp.Body.Close()
  822. return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
  823. }
  824. // GetBucketStat get bucket stat
  825. // bucketName the bucket name.
  826. // error it's nil if no error, otherwise it's an error object.
  827. func (client Client) GetBucketStat(bucketName string) (GetBucketStatResult, error) {
  828. var out GetBucketStatResult
  829. params := map[string]interface{}{}
  830. params["stat"] = nil
  831. resp, err := client.do("GET", bucketName, params, nil, nil)
  832. if err != nil {
  833. return out, err
  834. }
  835. defer resp.Body.Close()
  836. err = xmlUnmarshal(resp.Body, &out)
  837. return out, err
  838. }
  839. // GetBucketPolicy API operation for Object Storage Service.
  840. //
  841. // Get the policy from the bucket.
  842. //
  843. // bucketName the bucket name.
  844. //
  845. // string return the bucket's policy, and it's only valid when error is nil.
  846. //
  847. // error it's nil if no error, otherwise it's an error object.
  848. //
  849. func (client Client) GetBucketPolicy(bucketName string, options ...Option) (string, error) {
  850. params := map[string]interface{}{}
  851. params["policy"] = nil
  852. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  853. if err != nil {
  854. return "", err
  855. }
  856. defer resp.Body.Close()
  857. body, err := ioutil.ReadAll(resp.Body)
  858. out := string(body)
  859. return out, err
  860. }
  861. // SetBucketPolicy API operation for Object Storage Service.
  862. //
  863. // Set the policy from the bucket.
  864. //
  865. // bucketName the bucket name.
  866. //
  867. // policy the bucket policy.
  868. //
  869. // error it's nil if no error, otherwise it's an error object.
  870. //
  871. func (client Client) SetBucketPolicy(bucketName string, policy string, options ...Option) error {
  872. params := map[string]interface{}{}
  873. params["policy"] = nil
  874. buffer := strings.NewReader(policy)
  875. resp, err := client.do("PUT", bucketName, params, nil, buffer, options...)
  876. if err != nil {
  877. return err
  878. }
  879. defer resp.Body.Close()
  880. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  881. }
  882. // DeleteBucketPolicy API operation for Object Storage Service.
  883. //
  884. // Deletes the policy from the bucket.
  885. //
  886. // bucketName the bucket name.
  887. //
  888. // error it's nil if no error, otherwise it's an error object.
  889. //
  890. func (client Client) DeleteBucketPolicy(bucketName string, options ...Option) error {
  891. params := map[string]interface{}{}
  892. params["policy"] = nil
  893. resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
  894. if err != nil {
  895. return err
  896. }
  897. defer resp.Body.Close()
  898. return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
  899. }
  900. // SetBucketRequestPayment API operation for Object Storage Service.
  901. //
  902. // Set the requestPayment of bucket
  903. //
  904. // bucketName the bucket name.
  905. //
  906. // paymentConfig the payment configuration
  907. //
  908. // error it's nil if no error, otherwise it's an error object.
  909. //
  910. func (client Client) SetBucketRequestPayment(bucketName string, paymentConfig RequestPaymentConfiguration, options ...Option) error {
  911. params := map[string]interface{}{}
  912. params["requestPayment"] = nil
  913. var bs []byte
  914. bs, err := xml.Marshal(paymentConfig)
  915. if err != nil {
  916. return err
  917. }
  918. buffer := new(bytes.Buffer)
  919. buffer.Write(bs)
  920. contentType := http.DetectContentType(buffer.Bytes())
  921. headers := map[string]string{}
  922. headers[HTTPHeaderContentType] = contentType
  923. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  924. if err != nil {
  925. return err
  926. }
  927. defer resp.Body.Close()
  928. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  929. }
  930. // GetBucketRequestPayment API operation for Object Storage Service.
  931. //
  932. // Get bucket requestPayment
  933. //
  934. // bucketName the bucket name.
  935. //
  936. // RequestPaymentConfiguration the payment configuration
  937. //
  938. // error it's nil if no error, otherwise it's an error object.
  939. //
  940. func (client Client) GetBucketRequestPayment(bucketName string, options ...Option) (RequestPaymentConfiguration, error) {
  941. var out RequestPaymentConfiguration
  942. params := map[string]interface{}{}
  943. params["requestPayment"] = nil
  944. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  945. if err != nil {
  946. return out, err
  947. }
  948. defer resp.Body.Close()
  949. err = xmlUnmarshal(resp.Body, &out)
  950. return out, err
  951. }
  952. // GetUserQoSInfo API operation for Object Storage Service.
  953. //
  954. // Get user qos.
  955. //
  956. // UserQoSConfiguration the User Qos and range Information.
  957. //
  958. // error it's nil if no error, otherwise it's an error object.
  959. //
  960. func (client Client) GetUserQoSInfo(options ...Option) (UserQoSConfiguration, error) {
  961. var out UserQoSConfiguration
  962. params := map[string]interface{}{}
  963. params["qosInfo"] = nil
  964. resp, err := client.do("GET", "", params, nil, nil, options...)
  965. if err != nil {
  966. return out, err
  967. }
  968. defer resp.Body.Close()
  969. err = xmlUnmarshal(resp.Body, &out)
  970. return out, err
  971. }
  972. // SetBucketQoSInfo API operation for Object Storage Service.
  973. //
  974. // Set Bucket Qos information.
  975. //
  976. // bucketName tht bucket name.
  977. //
  978. // qosConf the qos configuration.
  979. //
  980. // error it's nil if no error, otherwise it's an error object.
  981. //
  982. func (client Client) SetBucketQoSInfo(bucketName string, qosConf BucketQoSConfiguration, options ...Option) error {
  983. params := map[string]interface{}{}
  984. params["qosInfo"] = nil
  985. var bs []byte
  986. bs, err := xml.Marshal(qosConf)
  987. if err != nil {
  988. return err
  989. }
  990. buffer := new(bytes.Buffer)
  991. buffer.Write(bs)
  992. contentTpye := http.DetectContentType(buffer.Bytes())
  993. headers := map[string]string{}
  994. headers[HTTPHeaderContentType] = contentTpye
  995. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  996. if err != nil {
  997. return err
  998. }
  999. defer resp.Body.Close()
  1000. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  1001. }
  1002. // GetBucketQosInfo API operation for Object Storage Service.
  1003. //
  1004. // Get Bucket Qos information.
  1005. //
  1006. // bucketName tht bucket name.
  1007. //
  1008. // BucketQoSConfiguration the return qos configuration.
  1009. //
  1010. // error it's nil if no error, otherwise it's an error object.
  1011. //
  1012. func (client Client) GetBucketQosInfo(bucketName string, options ...Option) (BucketQoSConfiguration, error) {
  1013. var out BucketQoSConfiguration
  1014. params := map[string]interface{}{}
  1015. params["qosInfo"] = nil
  1016. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  1017. if err != nil {
  1018. return out, err
  1019. }
  1020. defer resp.Body.Close()
  1021. err = xmlUnmarshal(resp.Body, &out)
  1022. return out, err
  1023. }
  1024. // DeleteBucketQosInfo API operation for Object Storage Service.
  1025. //
  1026. // Delete Bucket QoS information.
  1027. //
  1028. // bucketName tht bucket name.
  1029. //
  1030. // error it's nil if no error, otherwise it's an error object.
  1031. //
  1032. func (client Client) DeleteBucketQosInfo(bucketName string, options ...Option) error {
  1033. params := map[string]interface{}{}
  1034. params["qosInfo"] = nil
  1035. resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
  1036. if err != nil {
  1037. return err
  1038. }
  1039. defer resp.Body.Close()
  1040. return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
  1041. }
  1042. // LimitUploadSpeed set upload bandwidth limit speed,default is 0,unlimited
  1043. // upSpeed KB/s, 0 is unlimited,default is 0
  1044. // error it's nil if success, otherwise failure
  1045. func (client Client) LimitUploadSpeed(upSpeed int) error {
  1046. if client.Config == nil {
  1047. return fmt.Errorf("client config is nil")
  1048. }
  1049. return client.Config.LimitUploadSpeed(upSpeed)
  1050. }
  1051. // UseCname sets the flag of using CName. By default it's false.
  1052. //
  1053. // isUseCname true: the endpoint has the CName, false: the endpoint does not have cname. Default is false.
  1054. //
  1055. func UseCname(isUseCname bool) ClientOption {
  1056. return func(client *Client) {
  1057. client.Config.IsCname = isUseCname
  1058. client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
  1059. }
  1060. }
  1061. // Timeout sets the HTTP timeout in seconds.
  1062. //
  1063. // connectTimeoutSec HTTP timeout in seconds. Default is 10 seconds. 0 means infinite (not recommended)
  1064. // readWriteTimeout HTTP read or write's timeout in seconds. Default is 20 seconds. 0 means infinite.
  1065. //
  1066. func Timeout(connectTimeoutSec, readWriteTimeout int64) ClientOption {
  1067. return func(client *Client) {
  1068. client.Config.HTTPTimeout.ConnectTimeout =
  1069. time.Second * time.Duration(connectTimeoutSec)
  1070. client.Config.HTTPTimeout.ReadWriteTimeout =
  1071. time.Second * time.Duration(readWriteTimeout)
  1072. client.Config.HTTPTimeout.HeaderTimeout =
  1073. time.Second * time.Duration(readWriteTimeout)
  1074. client.Config.HTTPTimeout.IdleConnTimeout =
  1075. time.Second * time.Duration(readWriteTimeout)
  1076. client.Config.HTTPTimeout.LongTimeout =
  1077. time.Second * time.Duration(readWriteTimeout*10)
  1078. }
  1079. }
  1080. // SetBucketInventory API operation for Object Storage Service
  1081. //
  1082. // Set the Bucket inventory.
  1083. //
  1084. // bucketName tht bucket name.
  1085. //
  1086. // inventoryConfig the inventory configuration.
  1087. //
  1088. // error it's nil if no error, otherwise it's an error.
  1089. //
  1090. func (client Client) SetBucketInventory(bucketName string, inventoryConfig InventoryConfiguration, options ...Option) error {
  1091. params := map[string]interface{}{}
  1092. params["inventoryId"] = inventoryConfig.Id
  1093. params["inventory"] = nil
  1094. var bs []byte
  1095. bs, err := xml.Marshal(inventoryConfig)
  1096. if err != nil {
  1097. return err
  1098. }
  1099. buffer := new(bytes.Buffer)
  1100. buffer.Write(bs)
  1101. contentType := http.DetectContentType(buffer.Bytes())
  1102. headers := make(map[string]string)
  1103. headers[HTTPHeaderContentType] = contentType
  1104. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  1105. if err != nil {
  1106. return err
  1107. }
  1108. defer resp.Body.Close()
  1109. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  1110. }
  1111. // GetBucketInventory API operation for Object Storage Service
  1112. //
  1113. // Get the Bucket inventory.
  1114. //
  1115. // bucketName tht bucket name.
  1116. //
  1117. // strInventoryId the inventory id.
  1118. //
  1119. // InventoryConfiguration the inventory configuration.
  1120. //
  1121. // error it's nil if no error, otherwise it's an error.
  1122. //
  1123. func (client Client) GetBucketInventory(bucketName string, strInventoryId string, options ...Option) (InventoryConfiguration, error) {
  1124. var out InventoryConfiguration
  1125. params := map[string]interface{}{}
  1126. params["inventory"] = nil
  1127. params["inventoryId"] = strInventoryId
  1128. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  1129. if err != nil {
  1130. return out, err
  1131. }
  1132. defer resp.Body.Close()
  1133. err = xmlUnmarshal(resp.Body, &out)
  1134. return out, err
  1135. }
  1136. // ListBucketInventory API operation for Object Storage Service
  1137. //
  1138. // List the Bucket inventory.
  1139. //
  1140. // bucketName tht bucket name.
  1141. //
  1142. // continuationToken the users token.
  1143. //
  1144. // ListInventoryConfigurationsResult list all inventory configuration by .
  1145. //
  1146. // error it's nil if no error, otherwise it's an error.
  1147. //
  1148. func (client Client) ListBucketInventory(bucketName, continuationToken string, options ...Option) (ListInventoryConfigurationsResult, error) {
  1149. var out ListInventoryConfigurationsResult
  1150. params := map[string]interface{}{}
  1151. params["inventory"] = nil
  1152. if continuationToken == "" {
  1153. params["continuation-token"] = nil
  1154. } else {
  1155. params["continuation-token"] = continuationToken
  1156. }
  1157. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  1158. if err != nil {
  1159. return out, err
  1160. }
  1161. defer resp.Body.Close()
  1162. err = xmlUnmarshal(resp.Body, &out)
  1163. return out, err
  1164. }
  1165. // DeleteBucketInventory API operation for Object Storage Service.
  1166. //
  1167. // Delete Bucket inventory information.
  1168. //
  1169. // bucketName tht bucket name.
  1170. //
  1171. // strInventoryId the inventory id.
  1172. //
  1173. // error it's nil if no error, otherwise it's an error.
  1174. //
  1175. func (client Client) DeleteBucketInventory(bucketName, strInventoryId string, options ...Option) error {
  1176. params := map[string]interface{}{}
  1177. params["inventory"] = nil
  1178. params["inventoryId"] = strInventoryId
  1179. resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
  1180. if err != nil {
  1181. return err
  1182. }
  1183. defer resp.Body.Close()
  1184. return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
  1185. }
  1186. // SetBucketAsyncTask API operation for set async fetch task
  1187. //
  1188. // bucketName tht bucket name.
  1189. //
  1190. // asynConf configruation
  1191. //
  1192. // error it's nil if success, otherwise it's an error.
  1193. func (client Client) SetBucketAsyncTask(bucketName string, asynConf AsyncFetchTaskConfiguration, options ...Option) (AsyncFetchTaskResult, error) {
  1194. var out AsyncFetchTaskResult
  1195. params := map[string]interface{}{}
  1196. params["asyncFetch"] = nil
  1197. var bs []byte
  1198. bs, err := xml.Marshal(asynConf)
  1199. if err != nil {
  1200. return out, err
  1201. }
  1202. buffer := new(bytes.Buffer)
  1203. buffer.Write(bs)
  1204. contentType := http.DetectContentType(buffer.Bytes())
  1205. headers := make(map[string]string)
  1206. headers[HTTPHeaderContentType] = contentType
  1207. resp, err := client.do("POST", bucketName, params, headers, buffer, options...)
  1208. if err != nil {
  1209. return out, err
  1210. }
  1211. defer resp.Body.Close()
  1212. err = xmlUnmarshal(resp.Body, &out)
  1213. return out, err
  1214. }
  1215. // GetBucketAsyncTask API operation for set async fetch task
  1216. //
  1217. // bucketName tht bucket name.
  1218. //
  1219. // taskid returned by SetBucketAsyncTask
  1220. //
  1221. // error it's nil if success, otherwise it's an error.
  1222. func (client Client) GetBucketAsyncTask(bucketName string, taskID string, options ...Option) (AsynFetchTaskInfo, error) {
  1223. var out AsynFetchTaskInfo
  1224. params := map[string]interface{}{}
  1225. params["asyncFetch"] = nil
  1226. headers := make(map[string]string)
  1227. headers[HTTPHeaderOssTaskID] = taskID
  1228. resp, err := client.do("GET", bucketName, params, headers, nil, options...)
  1229. if err != nil {
  1230. return out, err
  1231. }
  1232. defer resp.Body.Close()
  1233. err = xmlUnmarshal(resp.Body, &out)
  1234. return out, err
  1235. }
  1236. // SecurityToken sets the temporary user's SecurityToken.
  1237. //
  1238. // token STS token
  1239. //
  1240. func SecurityToken(token string) ClientOption {
  1241. return func(client *Client) {
  1242. client.Config.SecurityToken = strings.TrimSpace(token)
  1243. }
  1244. }
  1245. // EnableMD5 enables MD5 validation.
  1246. //
  1247. // isEnableMD5 true: enable MD5 validation; false: disable MD5 validation.
  1248. //
  1249. func EnableMD5(isEnableMD5 bool) ClientOption {
  1250. return func(client *Client) {
  1251. client.Config.IsEnableMD5 = isEnableMD5
  1252. }
  1253. }
  1254. // MD5ThresholdCalcInMemory sets the memory usage threshold for computing the MD5, default is 16MB.
  1255. //
  1256. // threshold the memory threshold in bytes. When the uploaded content is more than 16MB, the temp file is used for computing the MD5.
  1257. //
  1258. func MD5ThresholdCalcInMemory(threshold int64) ClientOption {
  1259. return func(client *Client) {
  1260. client.Config.MD5Threshold = threshold
  1261. }
  1262. }
  1263. // EnableCRC enables the CRC checksum. Default is true.
  1264. //
  1265. // isEnableCRC true: enable CRC checksum; false: disable the CRC checksum.
  1266. //
  1267. func EnableCRC(isEnableCRC bool) ClientOption {
  1268. return func(client *Client) {
  1269. client.Config.IsEnableCRC = isEnableCRC
  1270. }
  1271. }
  1272. // UserAgent specifies UserAgent. The default is aliyun-sdk-go/1.2.0 (windows/-/amd64;go1.5.2).
  1273. //
  1274. // userAgent the user agent string.
  1275. //
  1276. func UserAgent(userAgent string) ClientOption {
  1277. return func(client *Client) {
  1278. client.Config.UserAgent = userAgent
  1279. client.Config.UserSetUa = true
  1280. }
  1281. }
  1282. // Proxy sets the proxy (optional). The default is not using proxy.
  1283. //
  1284. // proxyHost the proxy host in the format "host:port". For example, proxy.com:80 .
  1285. //
  1286. func Proxy(proxyHost string) ClientOption {
  1287. return func(client *Client) {
  1288. client.Config.IsUseProxy = true
  1289. client.Config.ProxyHost = proxyHost
  1290. client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
  1291. }
  1292. }
  1293. // AuthProxy sets the proxy information with user name and password.
  1294. //
  1295. // proxyHost the proxy host in the format "host:port". For example, proxy.com:80 .
  1296. // proxyUser the proxy user name.
  1297. // proxyPassword the proxy password.
  1298. //
  1299. func AuthProxy(proxyHost, proxyUser, proxyPassword string) ClientOption {
  1300. return func(client *Client) {
  1301. client.Config.IsUseProxy = true
  1302. client.Config.ProxyHost = proxyHost
  1303. client.Config.IsAuthProxy = true
  1304. client.Config.ProxyUser = proxyUser
  1305. client.Config.ProxyPassword = proxyPassword
  1306. client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
  1307. }
  1308. }
  1309. //
  1310. // HTTPClient sets the http.Client in use to the one passed in
  1311. //
  1312. func HTTPClient(HTTPClient *http.Client) ClientOption {
  1313. return func(client *Client) {
  1314. client.HTTPClient = HTTPClient
  1315. }
  1316. }
  1317. //
  1318. // SetLogLevel sets the oss sdk log level
  1319. //
  1320. func SetLogLevel(LogLevel int) ClientOption {
  1321. return func(client *Client) {
  1322. client.Config.LogLevel = LogLevel
  1323. }
  1324. }
  1325. //
  1326. // SetLogger sets the oss sdk logger
  1327. //
  1328. func SetLogger(Logger *log.Logger) ClientOption {
  1329. return func(client *Client) {
  1330. client.Config.Logger = Logger
  1331. }
  1332. }
  1333. // SetCredentialsProvider sets funciton for get the user's ak
  1334. func SetCredentialsProvider(provider CredentialsProvider) ClientOption {
  1335. return func(client *Client) {
  1336. client.Config.CredentialsProvider = provider
  1337. }
  1338. }
  1339. // SetLocalAddr sets funciton for local addr
  1340. func SetLocalAddr(localAddr net.Addr) ClientOption {
  1341. return func(client *Client) {
  1342. client.Config.LocalAddr = localAddr
  1343. }
  1344. }
  1345. // AuthVersion sets auth version: v1 or v2 signature which oss_server needed
  1346. func AuthVersion(authVersion AuthVersionType) ClientOption {
  1347. return func(client *Client) {
  1348. client.Config.AuthVersion = authVersion
  1349. }
  1350. }
  1351. // AdditionalHeaders sets special http headers needed to be signed
  1352. func AdditionalHeaders(headers []string) ClientOption {
  1353. return func(client *Client) {
  1354. client.Config.AdditionalHeaders = headers
  1355. }
  1356. }
  1357. // Private
  1358. func (client Client) do(method, bucketName string, params map[string]interface{},
  1359. headers map[string]string, data io.Reader, options ...Option) (*Response, error) {
  1360. err := CheckBucketName(bucketName)
  1361. if len(bucketName) > 0 && err != nil {
  1362. return nil, err
  1363. }
  1364. resp, err := client.Conn.Do(method, bucketName, "", params, headers, data, 0, nil)
  1365. // get response header
  1366. respHeader, _ := FindOption(options, responseHeader, nil)
  1367. if respHeader != nil {
  1368. pRespHeader := respHeader.(*http.Header)
  1369. *pRespHeader = resp.Headers
  1370. }
  1371. return resp, err
  1372. }