client.go 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596
  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. // NonVersionTransition is not suggested to use
  309. // to keep compatible
  310. for k, rule := range out.Rules {
  311. if len(rule.NonVersionTransitions) > 0 {
  312. out.Rules[k].NonVersionTransition = &(out.Rules[k].NonVersionTransitions[0])
  313. }
  314. }
  315. return out, err
  316. }
  317. // SetBucketReferer sets the bucket's referer whitelist and the flag if allowing empty referrer.
  318. //
  319. // 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
  320. // the allowing empty referrer flag. Note that this applies to requests from webbrowser only.
  321. // For example, for a bucket os-example and its referrer http://www.aliyun.com, all requests from this URL could access the bucket.
  322. // For more information, please check out this link :
  323. // https://help.aliyun.com/document_detail/oss/user_guide/security_management/referer.html
  324. //
  325. // bucketName the bucket name.
  326. // referers the referrer white list. A bucket could have a referrer list and each referrer supports one '*' and multiple '?' as wildcards.
  327. // The sample could be found in sample/bucket_referer.go
  328. // allowEmptyReferer the flag of allowing empty referrer. By default it's true.
  329. //
  330. // error it's nil if no error, otherwise it's an error object.
  331. //
  332. func (client Client) SetBucketReferer(bucketName string, referers []string, allowEmptyReferer bool) error {
  333. rxml := RefererXML{}
  334. rxml.AllowEmptyReferer = allowEmptyReferer
  335. if referers == nil {
  336. rxml.RefererList = append(rxml.RefererList, "")
  337. } else {
  338. for _, referer := range referers {
  339. rxml.RefererList = append(rxml.RefererList, referer)
  340. }
  341. }
  342. bs, err := xml.Marshal(rxml)
  343. if err != nil {
  344. return err
  345. }
  346. buffer := new(bytes.Buffer)
  347. buffer.Write(bs)
  348. contentType := http.DetectContentType(buffer.Bytes())
  349. headers := map[string]string{}
  350. headers[HTTPHeaderContentType] = contentType
  351. params := map[string]interface{}{}
  352. params["referer"] = nil
  353. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  354. if err != nil {
  355. return err
  356. }
  357. defer resp.Body.Close()
  358. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  359. }
  360. // GetBucketReferer gets the bucket's referrer white list.
  361. //
  362. // bucketName the bucket name.
  363. //
  364. // GetBucketRefererResponse the result object upon successful request. It's only valid when error is nil.
  365. // error it's nil if no error, otherwise it's an error object.
  366. //
  367. func (client Client) GetBucketReferer(bucketName string) (GetBucketRefererResult, error) {
  368. var out GetBucketRefererResult
  369. params := map[string]interface{}{}
  370. params["referer"] = nil
  371. resp, err := client.do("GET", bucketName, params, nil, nil)
  372. if err != nil {
  373. return out, err
  374. }
  375. defer resp.Body.Close()
  376. err = xmlUnmarshal(resp.Body, &out)
  377. return out, err
  378. }
  379. // SetBucketLogging sets the bucket logging settings.
  380. //
  381. // OSS could automatically store the access log. Only the bucket owner could enable the logging.
  382. // Once enabled, OSS would save all the access log into hourly log files in a specified bucket.
  383. // For more information, please check out https://help.aliyun.com/document_detail/oss/user_guide/security_management/logging.html
  384. //
  385. // bucketName bucket name to enable the log.
  386. // targetBucket the target bucket name to store the log files.
  387. // targetPrefix the log files' prefix.
  388. //
  389. // error it's nil if no error, otherwise it's an error object.
  390. //
  391. func (client Client) SetBucketLogging(bucketName, targetBucket, targetPrefix string,
  392. isEnable bool) error {
  393. var err error
  394. var bs []byte
  395. if isEnable {
  396. lxml := LoggingXML{}
  397. lxml.LoggingEnabled.TargetBucket = targetBucket
  398. lxml.LoggingEnabled.TargetPrefix = targetPrefix
  399. bs, err = xml.Marshal(lxml)
  400. } else {
  401. lxml := loggingXMLEmpty{}
  402. bs, err = xml.Marshal(lxml)
  403. }
  404. if err != nil {
  405. return err
  406. }
  407. buffer := new(bytes.Buffer)
  408. buffer.Write(bs)
  409. contentType := http.DetectContentType(buffer.Bytes())
  410. headers := map[string]string{}
  411. headers[HTTPHeaderContentType] = contentType
  412. params := map[string]interface{}{}
  413. params["logging"] = nil
  414. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  415. if err != nil {
  416. return err
  417. }
  418. defer resp.Body.Close()
  419. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  420. }
  421. // DeleteBucketLogging deletes the logging configuration to disable the logging on the bucket.
  422. //
  423. // bucketName the bucket name to disable the logging.
  424. //
  425. // error it's nil if no error, otherwise it's an error object.
  426. //
  427. func (client Client) DeleteBucketLogging(bucketName string) error {
  428. params := map[string]interface{}{}
  429. params["logging"] = nil
  430. resp, err := client.do("DELETE", bucketName, params, nil, nil)
  431. if err != nil {
  432. return err
  433. }
  434. defer resp.Body.Close()
  435. return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
  436. }
  437. // GetBucketLogging gets the bucket's logging settings
  438. //
  439. // bucketName the bucket name
  440. // GetBucketLoggingResponse the result object upon successful request. It's only valid when error is nil.
  441. //
  442. // error it's nil if no error, otherwise it's an error object.
  443. //
  444. func (client Client) GetBucketLogging(bucketName string) (GetBucketLoggingResult, error) {
  445. var out GetBucketLoggingResult
  446. params := map[string]interface{}{}
  447. params["logging"] = nil
  448. resp, err := client.do("GET", bucketName, params, nil, nil)
  449. if err != nil {
  450. return out, err
  451. }
  452. defer resp.Body.Close()
  453. err = xmlUnmarshal(resp.Body, &out)
  454. return out, err
  455. }
  456. // SetBucketWebsite sets the bucket's static website's index and error page.
  457. //
  458. // 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.
  459. // For more information, please check out: https://help.aliyun.com/document_detail/oss/user_guide/static_host_website.html
  460. //
  461. // bucketName the bucket name to enable static web site.
  462. // indexDocument index page.
  463. // errorDocument error page.
  464. //
  465. // error it's nil if no error, otherwise it's an error object.
  466. //
  467. func (client Client) SetBucketWebsite(bucketName, indexDocument, errorDocument string) error {
  468. wxml := WebsiteXML{}
  469. wxml.IndexDocument.Suffix = indexDocument
  470. wxml.ErrorDocument.Key = errorDocument
  471. bs, err := xml.Marshal(wxml)
  472. if err != nil {
  473. return err
  474. }
  475. buffer := new(bytes.Buffer)
  476. buffer.Write(bs)
  477. contentType := http.DetectContentType(buffer.Bytes())
  478. headers := make(map[string]string)
  479. headers[HTTPHeaderContentType] = contentType
  480. params := map[string]interface{}{}
  481. params["website"] = nil
  482. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  483. if err != nil {
  484. return err
  485. }
  486. defer resp.Body.Close()
  487. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  488. }
  489. // SetBucketWebsiteDetail sets the bucket's static website's detail
  490. //
  491. // 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.
  492. // For more information, please check out: https://help.aliyun.com/document_detail/oss/user_guide/static_host_website.html
  493. //
  494. // bucketName the bucket name to enable static web site.
  495. //
  496. // wxml the website's detail
  497. //
  498. // error it's nil if no error, otherwise it's an error object.
  499. //
  500. func (client Client) SetBucketWebsiteDetail(bucketName string, wxml WebsiteXML, options ...Option) error {
  501. bs, err := xml.Marshal(wxml)
  502. if err != nil {
  503. return err
  504. }
  505. buffer := new(bytes.Buffer)
  506. buffer.Write(bs)
  507. contentType := http.DetectContentType(buffer.Bytes())
  508. headers := make(map[string]string)
  509. headers[HTTPHeaderContentType] = contentType
  510. params := map[string]interface{}{}
  511. params["website"] = nil
  512. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  513. if err != nil {
  514. return err
  515. }
  516. defer resp.Body.Close()
  517. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  518. }
  519. // SetBucketWebsiteXml sets the bucket's static website's rule
  520. //
  521. // 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.
  522. // For more information, please check out: https://help.aliyun.com/document_detail/oss/user_guide/static_host_website.html
  523. //
  524. // bucketName the bucket name to enable static web site.
  525. //
  526. // wxml the website's detail
  527. //
  528. // error it's nil if no error, otherwise it's an error object.
  529. //
  530. func (client Client) SetBucketWebsiteXml(bucketName string, webXml string, options ...Option) error {
  531. buffer := new(bytes.Buffer)
  532. buffer.Write([]byte(webXml))
  533. contentType := http.DetectContentType(buffer.Bytes())
  534. headers := make(map[string]string)
  535. headers[HTTPHeaderContentType] = contentType
  536. params := map[string]interface{}{}
  537. params["website"] = nil
  538. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  539. if err != nil {
  540. return err
  541. }
  542. defer resp.Body.Close()
  543. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  544. }
  545. // DeleteBucketWebsite deletes the bucket's static web site settings.
  546. //
  547. // bucketName the bucket name.
  548. //
  549. // error it's nil if no error, otherwise it's an error object.
  550. //
  551. func (client Client) DeleteBucketWebsite(bucketName string) error {
  552. params := map[string]interface{}{}
  553. params["website"] = nil
  554. resp, err := client.do("DELETE", bucketName, params, nil, nil)
  555. if err != nil {
  556. return err
  557. }
  558. defer resp.Body.Close()
  559. return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
  560. }
  561. // GetBucketWebsite gets the bucket's default page (index page) and the error page.
  562. //
  563. // bucketName the bucket name
  564. //
  565. // GetBucketWebsiteResponse the result object upon successful request. It's only valid when error is nil.
  566. // error it's nil if no error, otherwise it's an error object.
  567. //
  568. func (client Client) GetBucketWebsite(bucketName string) (GetBucketWebsiteResult, error) {
  569. var out GetBucketWebsiteResult
  570. params := map[string]interface{}{}
  571. params["website"] = nil
  572. resp, err := client.do("GET", bucketName, params, nil, nil)
  573. if err != nil {
  574. return out, err
  575. }
  576. defer resp.Body.Close()
  577. err = xmlUnmarshal(resp.Body, &out)
  578. return out, err
  579. }
  580. // SetBucketCORS sets the bucket's CORS rules
  581. //
  582. // For more information, please check out https://help.aliyun.com/document_detail/oss/user_guide/security_management/cors.html
  583. //
  584. // bucketName the bucket name
  585. // corsRules the CORS rules to set. The related sample code is in sample/bucket_cors.go.
  586. //
  587. // error it's nil if no error, otherwise it's an error object.
  588. //
  589. func (client Client) SetBucketCORS(bucketName string, corsRules []CORSRule) error {
  590. corsxml := CORSXML{}
  591. for _, v := range corsRules {
  592. cr := CORSRule{}
  593. cr.AllowedMethod = v.AllowedMethod
  594. cr.AllowedOrigin = v.AllowedOrigin
  595. cr.AllowedHeader = v.AllowedHeader
  596. cr.ExposeHeader = v.ExposeHeader
  597. cr.MaxAgeSeconds = v.MaxAgeSeconds
  598. corsxml.CORSRules = append(corsxml.CORSRules, cr)
  599. }
  600. bs, err := xml.Marshal(corsxml)
  601. if err != nil {
  602. return err
  603. }
  604. buffer := new(bytes.Buffer)
  605. buffer.Write(bs)
  606. contentType := http.DetectContentType(buffer.Bytes())
  607. headers := map[string]string{}
  608. headers[HTTPHeaderContentType] = contentType
  609. params := map[string]interface{}{}
  610. params["cors"] = nil
  611. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  612. if err != nil {
  613. return err
  614. }
  615. defer resp.Body.Close()
  616. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  617. }
  618. // DeleteBucketCORS deletes the bucket's static website settings.
  619. //
  620. // bucketName the bucket name.
  621. //
  622. // error it's nil if no error, otherwise it's an error object.
  623. //
  624. func (client Client) DeleteBucketCORS(bucketName string) error {
  625. params := map[string]interface{}{}
  626. params["cors"] = nil
  627. resp, err := client.do("DELETE", bucketName, params, nil, nil)
  628. if err != nil {
  629. return err
  630. }
  631. defer resp.Body.Close()
  632. return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
  633. }
  634. // GetBucketCORS gets the bucket's CORS settings.
  635. //
  636. // bucketName the bucket name.
  637. // GetBucketCORSResult the result object upon successful request. It's only valid when error is nil.
  638. //
  639. // error it's nil if no error, otherwise it's an error object.
  640. //
  641. func (client Client) GetBucketCORS(bucketName string) (GetBucketCORSResult, error) {
  642. var out GetBucketCORSResult
  643. params := map[string]interface{}{}
  644. params["cors"] = nil
  645. resp, err := client.do("GET", bucketName, params, nil, nil)
  646. if err != nil {
  647. return out, err
  648. }
  649. defer resp.Body.Close()
  650. err = xmlUnmarshal(resp.Body, &out)
  651. return out, err
  652. }
  653. // GetBucketInfo gets the bucket information.
  654. //
  655. // bucketName the bucket name.
  656. // GetBucketInfoResult the result object upon successful request. It's only valid when error is nil.
  657. //
  658. // error it's nil if no error, otherwise it's an error object.
  659. //
  660. func (client Client) GetBucketInfo(bucketName string, options ...Option) (GetBucketInfoResult, error) {
  661. var out GetBucketInfoResult
  662. params := map[string]interface{}{}
  663. params["bucketInfo"] = nil
  664. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  665. if err != nil {
  666. return out, err
  667. }
  668. defer resp.Body.Close()
  669. err = xmlUnmarshal(resp.Body, &out)
  670. // convert None to ""
  671. if err == nil {
  672. if out.BucketInfo.SseRule.KMSMasterKeyID == "None" {
  673. out.BucketInfo.SseRule.KMSMasterKeyID = ""
  674. }
  675. if out.BucketInfo.SseRule.SSEAlgorithm == "None" {
  676. out.BucketInfo.SseRule.SSEAlgorithm = ""
  677. }
  678. if out.BucketInfo.SseRule.KMSDataEncryption == "None" {
  679. out.BucketInfo.SseRule.KMSDataEncryption = ""
  680. }
  681. }
  682. return out, err
  683. }
  684. // SetBucketVersioning set bucket versioning:Enabled、Suspended
  685. // bucketName the bucket name.
  686. // error it's nil if no error, otherwise it's an error object.
  687. func (client Client) SetBucketVersioning(bucketName string, versioningConfig VersioningConfig, options ...Option) error {
  688. var err error
  689. var bs []byte
  690. bs, err = xml.Marshal(versioningConfig)
  691. if err != nil {
  692. return err
  693. }
  694. buffer := new(bytes.Buffer)
  695. buffer.Write(bs)
  696. contentType := http.DetectContentType(buffer.Bytes())
  697. headers := map[string]string{}
  698. headers[HTTPHeaderContentType] = contentType
  699. params := map[string]interface{}{}
  700. params["versioning"] = nil
  701. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  702. if err != nil {
  703. return err
  704. }
  705. defer resp.Body.Close()
  706. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  707. }
  708. // GetBucketVersioning get bucket versioning status:Enabled、Suspended
  709. // bucketName the bucket name.
  710. // error it's nil if no error, otherwise it's an error object.
  711. func (client Client) GetBucketVersioning(bucketName string, options ...Option) (GetBucketVersioningResult, error) {
  712. var out GetBucketVersioningResult
  713. params := map[string]interface{}{}
  714. params["versioning"] = nil
  715. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  716. if err != nil {
  717. return out, err
  718. }
  719. defer resp.Body.Close()
  720. err = xmlUnmarshal(resp.Body, &out)
  721. return out, err
  722. }
  723. // SetBucketEncryption set bucket encryption config
  724. // bucketName the bucket name.
  725. // error it's nil if no error, otherwise it's an error object.
  726. func (client Client) SetBucketEncryption(bucketName string, encryptionRule ServerEncryptionRule, options ...Option) error {
  727. var err error
  728. var bs []byte
  729. bs, err = xml.Marshal(encryptionRule)
  730. if err != nil {
  731. return err
  732. }
  733. buffer := new(bytes.Buffer)
  734. buffer.Write(bs)
  735. contentType := http.DetectContentType(buffer.Bytes())
  736. headers := map[string]string{}
  737. headers[HTTPHeaderContentType] = contentType
  738. params := map[string]interface{}{}
  739. params["encryption"] = nil
  740. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  741. if err != nil {
  742. return err
  743. }
  744. defer resp.Body.Close()
  745. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  746. }
  747. // GetBucketEncryption get bucket encryption
  748. // bucketName the bucket name.
  749. // error it's nil if no error, otherwise it's an error object.
  750. func (client Client) GetBucketEncryption(bucketName string, options ...Option) (GetBucketEncryptionResult, error) {
  751. var out GetBucketEncryptionResult
  752. params := map[string]interface{}{}
  753. params["encryption"] = nil
  754. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  755. if err != nil {
  756. return out, err
  757. }
  758. defer resp.Body.Close()
  759. err = xmlUnmarshal(resp.Body, &out)
  760. return out, err
  761. }
  762. // DeleteBucketEncryption delete bucket encryption config
  763. // bucketName the bucket name.
  764. // error it's nil if no error, otherwise it's an error bucket
  765. func (client Client) DeleteBucketEncryption(bucketName string, options ...Option) error {
  766. params := map[string]interface{}{}
  767. params["encryption"] = nil
  768. resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
  769. if err != nil {
  770. return err
  771. }
  772. defer resp.Body.Close()
  773. return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
  774. }
  775. //
  776. // SetBucketTagging add tagging to bucket
  777. // bucketName name of bucket
  778. // tagging tagging to be added
  779. // error nil if success, otherwise error
  780. func (client Client) SetBucketTagging(bucketName string, tagging Tagging, options ...Option) error {
  781. var err error
  782. var bs []byte
  783. bs, err = xml.Marshal(tagging)
  784. if err != nil {
  785. return err
  786. }
  787. buffer := new(bytes.Buffer)
  788. buffer.Write(bs)
  789. contentType := http.DetectContentType(buffer.Bytes())
  790. headers := map[string]string{}
  791. headers[HTTPHeaderContentType] = contentType
  792. params := map[string]interface{}{}
  793. params["tagging"] = nil
  794. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  795. if err != nil {
  796. return err
  797. }
  798. defer resp.Body.Close()
  799. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  800. }
  801. // GetBucketTagging get tagging of the bucket
  802. // bucketName name of bucket
  803. // error nil if success, otherwise error
  804. func (client Client) GetBucketTagging(bucketName string, options ...Option) (GetBucketTaggingResult, error) {
  805. var out GetBucketTaggingResult
  806. params := map[string]interface{}{}
  807. params["tagging"] = nil
  808. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  809. if err != nil {
  810. return out, err
  811. }
  812. defer resp.Body.Close()
  813. err = xmlUnmarshal(resp.Body, &out)
  814. return out, err
  815. }
  816. //
  817. // DeleteBucketTagging delete bucket tagging
  818. // bucketName name of bucket
  819. // error nil if success, otherwise error
  820. //
  821. func (client Client) DeleteBucketTagging(bucketName string, options ...Option) error {
  822. params := map[string]interface{}{}
  823. params["tagging"] = nil
  824. resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
  825. if err != nil {
  826. return err
  827. }
  828. defer resp.Body.Close()
  829. return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
  830. }
  831. // GetBucketStat get bucket stat
  832. // bucketName the bucket name.
  833. // error it's nil if no error, otherwise it's an error object.
  834. func (client Client) GetBucketStat(bucketName string) (GetBucketStatResult, error) {
  835. var out GetBucketStatResult
  836. params := map[string]interface{}{}
  837. params["stat"] = nil
  838. resp, err := client.do("GET", bucketName, params, nil, nil)
  839. if err != nil {
  840. return out, err
  841. }
  842. defer resp.Body.Close()
  843. err = xmlUnmarshal(resp.Body, &out)
  844. return out, err
  845. }
  846. // GetBucketPolicy API operation for Object Storage Service.
  847. //
  848. // Get the policy from the bucket.
  849. //
  850. // bucketName the bucket name.
  851. //
  852. // string return the bucket's policy, and it's only valid when error is nil.
  853. //
  854. // error it's nil if no error, otherwise it's an error object.
  855. //
  856. func (client Client) GetBucketPolicy(bucketName string, options ...Option) (string, error) {
  857. params := map[string]interface{}{}
  858. params["policy"] = nil
  859. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  860. if err != nil {
  861. return "", err
  862. }
  863. defer resp.Body.Close()
  864. body, err := ioutil.ReadAll(resp.Body)
  865. out := string(body)
  866. return out, err
  867. }
  868. // SetBucketPolicy API operation for Object Storage Service.
  869. //
  870. // Set the policy from the bucket.
  871. //
  872. // bucketName the bucket name.
  873. //
  874. // policy the bucket policy.
  875. //
  876. // error it's nil if no error, otherwise it's an error object.
  877. //
  878. func (client Client) SetBucketPolicy(bucketName string, policy string, options ...Option) error {
  879. params := map[string]interface{}{}
  880. params["policy"] = nil
  881. buffer := strings.NewReader(policy)
  882. resp, err := client.do("PUT", bucketName, params, nil, buffer, options...)
  883. if err != nil {
  884. return err
  885. }
  886. defer resp.Body.Close()
  887. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  888. }
  889. // DeleteBucketPolicy API operation for Object Storage Service.
  890. //
  891. // Deletes the policy from the bucket.
  892. //
  893. // bucketName the bucket name.
  894. //
  895. // error it's nil if no error, otherwise it's an error object.
  896. //
  897. func (client Client) DeleteBucketPolicy(bucketName string, options ...Option) error {
  898. params := map[string]interface{}{}
  899. params["policy"] = nil
  900. resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
  901. if err != nil {
  902. return err
  903. }
  904. defer resp.Body.Close()
  905. return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
  906. }
  907. // SetBucketRequestPayment API operation for Object Storage Service.
  908. //
  909. // Set the requestPayment of bucket
  910. //
  911. // bucketName the bucket name.
  912. //
  913. // paymentConfig the payment configuration
  914. //
  915. // error it's nil if no error, otherwise it's an error object.
  916. //
  917. func (client Client) SetBucketRequestPayment(bucketName string, paymentConfig RequestPaymentConfiguration, options ...Option) error {
  918. params := map[string]interface{}{}
  919. params["requestPayment"] = nil
  920. var bs []byte
  921. bs, err := xml.Marshal(paymentConfig)
  922. if err != nil {
  923. return err
  924. }
  925. buffer := new(bytes.Buffer)
  926. buffer.Write(bs)
  927. contentType := http.DetectContentType(buffer.Bytes())
  928. headers := map[string]string{}
  929. headers[HTTPHeaderContentType] = contentType
  930. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  931. if err != nil {
  932. return err
  933. }
  934. defer resp.Body.Close()
  935. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  936. }
  937. // GetBucketRequestPayment API operation for Object Storage Service.
  938. //
  939. // Get bucket requestPayment
  940. //
  941. // bucketName the bucket name.
  942. //
  943. // RequestPaymentConfiguration the payment configuration
  944. //
  945. // error it's nil if no error, otherwise it's an error object.
  946. //
  947. func (client Client) GetBucketRequestPayment(bucketName string, options ...Option) (RequestPaymentConfiguration, error) {
  948. var out RequestPaymentConfiguration
  949. params := map[string]interface{}{}
  950. params["requestPayment"] = nil
  951. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  952. if err != nil {
  953. return out, err
  954. }
  955. defer resp.Body.Close()
  956. err = xmlUnmarshal(resp.Body, &out)
  957. return out, err
  958. }
  959. // GetUserQoSInfo API operation for Object Storage Service.
  960. //
  961. // Get user qos.
  962. //
  963. // UserQoSConfiguration the User Qos and range Information.
  964. //
  965. // error it's nil if no error, otherwise it's an error object.
  966. //
  967. func (client Client) GetUserQoSInfo(options ...Option) (UserQoSConfiguration, error) {
  968. var out UserQoSConfiguration
  969. params := map[string]interface{}{}
  970. params["qosInfo"] = nil
  971. resp, err := client.do("GET", "", params, nil, nil, options...)
  972. if err != nil {
  973. return out, err
  974. }
  975. defer resp.Body.Close()
  976. err = xmlUnmarshal(resp.Body, &out)
  977. return out, err
  978. }
  979. // SetBucketQoSInfo API operation for Object Storage Service.
  980. //
  981. // Set Bucket Qos information.
  982. //
  983. // bucketName tht bucket name.
  984. //
  985. // qosConf the qos configuration.
  986. //
  987. // error it's nil if no error, otherwise it's an error object.
  988. //
  989. func (client Client) SetBucketQoSInfo(bucketName string, qosConf BucketQoSConfiguration, options ...Option) error {
  990. params := map[string]interface{}{}
  991. params["qosInfo"] = nil
  992. var bs []byte
  993. bs, err := xml.Marshal(qosConf)
  994. if err != nil {
  995. return err
  996. }
  997. buffer := new(bytes.Buffer)
  998. buffer.Write(bs)
  999. contentTpye := http.DetectContentType(buffer.Bytes())
  1000. headers := map[string]string{}
  1001. headers[HTTPHeaderContentType] = contentTpye
  1002. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  1003. if err != nil {
  1004. return err
  1005. }
  1006. defer resp.Body.Close()
  1007. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  1008. }
  1009. // GetBucketQosInfo API operation for Object Storage Service.
  1010. //
  1011. // Get Bucket Qos information.
  1012. //
  1013. // bucketName tht bucket name.
  1014. //
  1015. // BucketQoSConfiguration the return qos configuration.
  1016. //
  1017. // error it's nil if no error, otherwise it's an error object.
  1018. //
  1019. func (client Client) GetBucketQosInfo(bucketName string, options ...Option) (BucketQoSConfiguration, error) {
  1020. var out BucketQoSConfiguration
  1021. params := map[string]interface{}{}
  1022. params["qosInfo"] = nil
  1023. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  1024. if err != nil {
  1025. return out, err
  1026. }
  1027. defer resp.Body.Close()
  1028. err = xmlUnmarshal(resp.Body, &out)
  1029. return out, err
  1030. }
  1031. // DeleteBucketQosInfo API operation for Object Storage Service.
  1032. //
  1033. // Delete Bucket QoS information.
  1034. //
  1035. // bucketName tht bucket name.
  1036. //
  1037. // error it's nil if no error, otherwise it's an error object.
  1038. //
  1039. func (client Client) DeleteBucketQosInfo(bucketName string, options ...Option) error {
  1040. params := map[string]interface{}{}
  1041. params["qosInfo"] = nil
  1042. resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
  1043. if err != nil {
  1044. return err
  1045. }
  1046. defer resp.Body.Close()
  1047. return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
  1048. }
  1049. // LimitUploadSpeed set upload bandwidth limit speed,default is 0,unlimited
  1050. // upSpeed KB/s, 0 is unlimited,default is 0
  1051. // error it's nil if success, otherwise failure
  1052. func (client Client) LimitUploadSpeed(upSpeed int) error {
  1053. if client.Config == nil {
  1054. return fmt.Errorf("client config is nil")
  1055. }
  1056. return client.Config.LimitUploadSpeed(upSpeed)
  1057. }
  1058. // UseCname sets the flag of using CName. By default it's false.
  1059. //
  1060. // isUseCname true: the endpoint has the CName, false: the endpoint does not have cname. Default is false.
  1061. //
  1062. func UseCname(isUseCname bool) ClientOption {
  1063. return func(client *Client) {
  1064. client.Config.IsCname = isUseCname
  1065. client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
  1066. }
  1067. }
  1068. // Timeout sets the HTTP timeout in seconds.
  1069. //
  1070. // connectTimeoutSec HTTP timeout in seconds. Default is 10 seconds. 0 means infinite (not recommended)
  1071. // readWriteTimeout HTTP read or write's timeout in seconds. Default is 20 seconds. 0 means infinite.
  1072. //
  1073. func Timeout(connectTimeoutSec, readWriteTimeout int64) ClientOption {
  1074. return func(client *Client) {
  1075. client.Config.HTTPTimeout.ConnectTimeout =
  1076. time.Second * time.Duration(connectTimeoutSec)
  1077. client.Config.HTTPTimeout.ReadWriteTimeout =
  1078. time.Second * time.Duration(readWriteTimeout)
  1079. client.Config.HTTPTimeout.HeaderTimeout =
  1080. time.Second * time.Duration(readWriteTimeout)
  1081. client.Config.HTTPTimeout.IdleConnTimeout =
  1082. time.Second * time.Duration(readWriteTimeout)
  1083. client.Config.HTTPTimeout.LongTimeout =
  1084. time.Second * time.Duration(readWriteTimeout*10)
  1085. }
  1086. }
  1087. // SetBucketInventory API operation for Object Storage Service
  1088. //
  1089. // Set the Bucket inventory.
  1090. //
  1091. // bucketName tht bucket name.
  1092. //
  1093. // inventoryConfig the inventory configuration.
  1094. //
  1095. // error it's nil if no error, otherwise it's an error.
  1096. //
  1097. func (client Client) SetBucketInventory(bucketName string, inventoryConfig InventoryConfiguration, options ...Option) error {
  1098. params := map[string]interface{}{}
  1099. params["inventoryId"] = inventoryConfig.Id
  1100. params["inventory"] = nil
  1101. var bs []byte
  1102. bs, err := xml.Marshal(inventoryConfig)
  1103. if err != nil {
  1104. return err
  1105. }
  1106. buffer := new(bytes.Buffer)
  1107. buffer.Write(bs)
  1108. contentType := http.DetectContentType(buffer.Bytes())
  1109. headers := make(map[string]string)
  1110. headers[HTTPHeaderContentType] = contentType
  1111. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  1112. if err != nil {
  1113. return err
  1114. }
  1115. defer resp.Body.Close()
  1116. return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
  1117. }
  1118. // GetBucketInventory API operation for Object Storage Service
  1119. //
  1120. // Get the Bucket inventory.
  1121. //
  1122. // bucketName tht bucket name.
  1123. //
  1124. // strInventoryId the inventory id.
  1125. //
  1126. // InventoryConfiguration the inventory configuration.
  1127. //
  1128. // error it's nil if no error, otherwise it's an error.
  1129. //
  1130. func (client Client) GetBucketInventory(bucketName string, strInventoryId string, options ...Option) (InventoryConfiguration, error) {
  1131. var out InventoryConfiguration
  1132. params := map[string]interface{}{}
  1133. params["inventory"] = nil
  1134. params["inventoryId"] = strInventoryId
  1135. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  1136. if err != nil {
  1137. return out, err
  1138. }
  1139. defer resp.Body.Close()
  1140. err = xmlUnmarshal(resp.Body, &out)
  1141. return out, err
  1142. }
  1143. // ListBucketInventory API operation for Object Storage Service
  1144. //
  1145. // List the Bucket inventory.
  1146. //
  1147. // bucketName tht bucket name.
  1148. //
  1149. // continuationToken the users token.
  1150. //
  1151. // ListInventoryConfigurationsResult list all inventory configuration by .
  1152. //
  1153. // error it's nil if no error, otherwise it's an error.
  1154. //
  1155. func (client Client) ListBucketInventory(bucketName, continuationToken string, options ...Option) (ListInventoryConfigurationsResult, error) {
  1156. var out ListInventoryConfigurationsResult
  1157. params := map[string]interface{}{}
  1158. params["inventory"] = nil
  1159. if continuationToken == "" {
  1160. params["continuation-token"] = nil
  1161. } else {
  1162. params["continuation-token"] = continuationToken
  1163. }
  1164. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  1165. if err != nil {
  1166. return out, err
  1167. }
  1168. defer resp.Body.Close()
  1169. err = xmlUnmarshal(resp.Body, &out)
  1170. return out, err
  1171. }
  1172. // DeleteBucketInventory API operation for Object Storage Service.
  1173. //
  1174. // Delete Bucket inventory information.
  1175. //
  1176. // bucketName tht bucket name.
  1177. //
  1178. // strInventoryId the inventory id.
  1179. //
  1180. // error it's nil if no error, otherwise it's an error.
  1181. //
  1182. func (client Client) DeleteBucketInventory(bucketName, strInventoryId string, options ...Option) error {
  1183. params := map[string]interface{}{}
  1184. params["inventory"] = nil
  1185. params["inventoryId"] = strInventoryId
  1186. resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
  1187. if err != nil {
  1188. return err
  1189. }
  1190. defer resp.Body.Close()
  1191. return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
  1192. }
  1193. // SetBucketAsyncTask API operation for set async fetch task
  1194. //
  1195. // bucketName tht bucket name.
  1196. //
  1197. // asynConf configruation
  1198. //
  1199. // error it's nil if success, otherwise it's an error.
  1200. func (client Client) SetBucketAsyncTask(bucketName string, asynConf AsyncFetchTaskConfiguration, options ...Option) (AsyncFetchTaskResult, error) {
  1201. var out AsyncFetchTaskResult
  1202. params := map[string]interface{}{}
  1203. params["asyncFetch"] = nil
  1204. var bs []byte
  1205. bs, err := xml.Marshal(asynConf)
  1206. if err != nil {
  1207. return out, err
  1208. }
  1209. buffer := new(bytes.Buffer)
  1210. buffer.Write(bs)
  1211. contentType := http.DetectContentType(buffer.Bytes())
  1212. headers := make(map[string]string)
  1213. headers[HTTPHeaderContentType] = contentType
  1214. resp, err := client.do("POST", bucketName, params, headers, buffer, options...)
  1215. if err != nil {
  1216. return out, err
  1217. }
  1218. defer resp.Body.Close()
  1219. err = xmlUnmarshal(resp.Body, &out)
  1220. return out, err
  1221. }
  1222. // GetBucketAsyncTask API operation for set async fetch task
  1223. //
  1224. // bucketName tht bucket name.
  1225. //
  1226. // taskid returned by SetBucketAsyncTask
  1227. //
  1228. // error it's nil if success, otherwise it's an error.
  1229. func (client Client) GetBucketAsyncTask(bucketName string, taskID string, options ...Option) (AsynFetchTaskInfo, error) {
  1230. var out AsynFetchTaskInfo
  1231. params := map[string]interface{}{}
  1232. params["asyncFetch"] = nil
  1233. headers := make(map[string]string)
  1234. headers[HTTPHeaderOssTaskID] = taskID
  1235. resp, err := client.do("GET", bucketName, params, headers, nil, options...)
  1236. if err != nil {
  1237. return out, err
  1238. }
  1239. defer resp.Body.Close()
  1240. err = xmlUnmarshal(resp.Body, &out)
  1241. return out, err
  1242. }
  1243. // SecurityToken sets the temporary user's SecurityToken.
  1244. //
  1245. // token STS token
  1246. //
  1247. func SecurityToken(token string) ClientOption {
  1248. return func(client *Client) {
  1249. client.Config.SecurityToken = strings.TrimSpace(token)
  1250. }
  1251. }
  1252. // EnableMD5 enables MD5 validation.
  1253. //
  1254. // isEnableMD5 true: enable MD5 validation; false: disable MD5 validation.
  1255. //
  1256. func EnableMD5(isEnableMD5 bool) ClientOption {
  1257. return func(client *Client) {
  1258. client.Config.IsEnableMD5 = isEnableMD5
  1259. }
  1260. }
  1261. // MD5ThresholdCalcInMemory sets the memory usage threshold for computing the MD5, default is 16MB.
  1262. //
  1263. // threshold the memory threshold in bytes. When the uploaded content is more than 16MB, the temp file is used for computing the MD5.
  1264. //
  1265. func MD5ThresholdCalcInMemory(threshold int64) ClientOption {
  1266. return func(client *Client) {
  1267. client.Config.MD5Threshold = threshold
  1268. }
  1269. }
  1270. // EnableCRC enables the CRC checksum. Default is true.
  1271. //
  1272. // isEnableCRC true: enable CRC checksum; false: disable the CRC checksum.
  1273. //
  1274. func EnableCRC(isEnableCRC bool) ClientOption {
  1275. return func(client *Client) {
  1276. client.Config.IsEnableCRC = isEnableCRC
  1277. }
  1278. }
  1279. // UserAgent specifies UserAgent. The default is aliyun-sdk-go/1.2.0 (windows/-/amd64;go1.5.2).
  1280. //
  1281. // userAgent the user agent string.
  1282. //
  1283. func UserAgent(userAgent string) ClientOption {
  1284. return func(client *Client) {
  1285. client.Config.UserAgent = userAgent
  1286. client.Config.UserSetUa = true
  1287. }
  1288. }
  1289. // Proxy sets the proxy (optional). The default is not using proxy.
  1290. //
  1291. // proxyHost the proxy host in the format "host:port". For example, proxy.com:80 .
  1292. //
  1293. func Proxy(proxyHost string) ClientOption {
  1294. return func(client *Client) {
  1295. client.Config.IsUseProxy = true
  1296. client.Config.ProxyHost = proxyHost
  1297. client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
  1298. }
  1299. }
  1300. // AuthProxy sets the proxy information with user name and password.
  1301. //
  1302. // proxyHost the proxy host in the format "host:port". For example, proxy.com:80 .
  1303. // proxyUser the proxy user name.
  1304. // proxyPassword the proxy password.
  1305. //
  1306. func AuthProxy(proxyHost, proxyUser, proxyPassword string) ClientOption {
  1307. return func(client *Client) {
  1308. client.Config.IsUseProxy = true
  1309. client.Config.ProxyHost = proxyHost
  1310. client.Config.IsAuthProxy = true
  1311. client.Config.ProxyUser = proxyUser
  1312. client.Config.ProxyPassword = proxyPassword
  1313. client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
  1314. }
  1315. }
  1316. //
  1317. // HTTPClient sets the http.Client in use to the one passed in
  1318. //
  1319. func HTTPClient(HTTPClient *http.Client) ClientOption {
  1320. return func(client *Client) {
  1321. client.HTTPClient = HTTPClient
  1322. }
  1323. }
  1324. //
  1325. // SetLogLevel sets the oss sdk log level
  1326. //
  1327. func SetLogLevel(LogLevel int) ClientOption {
  1328. return func(client *Client) {
  1329. client.Config.LogLevel = LogLevel
  1330. }
  1331. }
  1332. //
  1333. // SetLogger sets the oss sdk logger
  1334. //
  1335. func SetLogger(Logger *log.Logger) ClientOption {
  1336. return func(client *Client) {
  1337. client.Config.Logger = Logger
  1338. }
  1339. }
  1340. // SetCredentialsProvider sets funciton for get the user's ak
  1341. func SetCredentialsProvider(provider CredentialsProvider) ClientOption {
  1342. return func(client *Client) {
  1343. client.Config.CredentialsProvider = provider
  1344. }
  1345. }
  1346. // SetLocalAddr sets funciton for local addr
  1347. func SetLocalAddr(localAddr net.Addr) ClientOption {
  1348. return func(client *Client) {
  1349. client.Config.LocalAddr = localAddr
  1350. }
  1351. }
  1352. // AuthVersion sets auth version: v1 or v2 signature which oss_server needed
  1353. func AuthVersion(authVersion AuthVersionType) ClientOption {
  1354. return func(client *Client) {
  1355. client.Config.AuthVersion = authVersion
  1356. }
  1357. }
  1358. // AdditionalHeaders sets special http headers needed to be signed
  1359. func AdditionalHeaders(headers []string) ClientOption {
  1360. return func(client *Client) {
  1361. client.Config.AdditionalHeaders = headers
  1362. }
  1363. }
  1364. // only effective from go1.7 onward,RedirectEnabled set http redirect enabled or not
  1365. func RedirectEnabled(enabled bool) ClientOption {
  1366. return func(client *Client) {
  1367. client.Config.RedirectEnabled = enabled
  1368. }
  1369. }
  1370. // Private
  1371. func (client Client) do(method, bucketName string, params map[string]interface{},
  1372. headers map[string]string, data io.Reader, options ...Option) (*Response, error) {
  1373. err := CheckBucketName(bucketName)
  1374. if len(bucketName) > 0 && err != nil {
  1375. return nil, err
  1376. }
  1377. // option headers
  1378. addHeaders := make(map[string]string)
  1379. err = handleOptions(addHeaders, options)
  1380. if err != nil {
  1381. return nil, err
  1382. }
  1383. // merge header
  1384. if headers == nil {
  1385. headers = make(map[string]string)
  1386. }
  1387. for k, v := range addHeaders {
  1388. if _, ok := headers[k]; !ok {
  1389. headers[k] = v
  1390. }
  1391. }
  1392. resp, err := client.Conn.Do(method, bucketName, "", params, headers, data, 0, nil)
  1393. // get response header
  1394. respHeader, _ := FindOption(options, responseHeader, nil)
  1395. if respHeader != nil {
  1396. pRespHeader := respHeader.(*http.Header)
  1397. *pRespHeader = resp.Headers
  1398. }
  1399. return resp, err
  1400. }