client.go 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498
  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. }
  672. return out, err
  673. }
  674. // SetBucketVersioning set bucket versioning:Enabled、Suspended
  675. // bucketName the bucket name.
  676. // error it's nil if no error, otherwise it's an error object.
  677. func (client Client) SetBucketVersioning(bucketName string, versioningConfig VersioningConfig, options ...Option) error {
  678. var err error
  679. var bs []byte
  680. bs, err = xml.Marshal(versioningConfig)
  681. if err != nil {
  682. return err
  683. }
  684. buffer := new(bytes.Buffer)
  685. buffer.Write(bs)
  686. contentType := http.DetectContentType(buffer.Bytes())
  687. headers := map[string]string{}
  688. headers[HTTPHeaderContentType] = contentType
  689. params := map[string]interface{}{}
  690. params["versioning"] = nil
  691. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  692. if err != nil {
  693. return err
  694. }
  695. defer resp.Body.Close()
  696. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  697. }
  698. // GetBucketVersioning get bucket versioning status:Enabled、Suspended
  699. // bucketName the bucket name.
  700. // error it's nil if no error, otherwise it's an error object.
  701. func (client Client) GetBucketVersioning(bucketName string, options ...Option) (GetBucketVersioningResult, error) {
  702. var out GetBucketVersioningResult
  703. params := map[string]interface{}{}
  704. params["versioning"] = nil
  705. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  706. if err != nil {
  707. return out, err
  708. }
  709. defer resp.Body.Close()
  710. err = xmlUnmarshal(resp.Body, &out)
  711. return out, err
  712. }
  713. // SetBucketEncryption set bucket encryption config
  714. // bucketName the bucket name.
  715. // error it's nil if no error, otherwise it's an error object.
  716. func (client Client) SetBucketEncryption(bucketName string, encryptionRule ServerEncryptionRule, options ...Option) error {
  717. var err error
  718. var bs []byte
  719. bs, err = xml.Marshal(encryptionRule)
  720. if err != nil {
  721. return err
  722. }
  723. buffer := new(bytes.Buffer)
  724. buffer.Write(bs)
  725. contentType := http.DetectContentType(buffer.Bytes())
  726. headers := map[string]string{}
  727. headers[HTTPHeaderContentType] = contentType
  728. params := map[string]interface{}{}
  729. params["encryption"] = nil
  730. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  731. if err != nil {
  732. return err
  733. }
  734. defer resp.Body.Close()
  735. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  736. }
  737. // GetBucketEncryption get bucket encryption
  738. // bucketName the bucket name.
  739. // error it's nil if no error, otherwise it's an error object.
  740. func (client Client) GetBucketEncryption(bucketName string, options ...Option) (GetBucketEncryptionResult, error) {
  741. var out GetBucketEncryptionResult
  742. params := map[string]interface{}{}
  743. params["encryption"] = nil
  744. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  745. if err != nil {
  746. return out, err
  747. }
  748. defer resp.Body.Close()
  749. err = xmlUnmarshal(resp.Body, &out)
  750. return out, err
  751. }
  752. // DeleteBucketEncryption delete bucket encryption config
  753. // bucketName the bucket name.
  754. // error it's nil if no error, otherwise it's an error bucket
  755. func (client Client) DeleteBucketEncryption(bucketName string, options ...Option) error {
  756. params := map[string]interface{}{}
  757. params["encryption"] = nil
  758. resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
  759. if err != nil {
  760. return err
  761. }
  762. defer resp.Body.Close()
  763. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  764. }
  765. //
  766. // SetBucketTagging add tagging to bucket
  767. // bucketName name of bucket
  768. // tagging tagging to be added
  769. // error nil if success, otherwise error
  770. func (client Client) SetBucketTagging(bucketName string, tagging Tagging, options ...Option) error {
  771. var err error
  772. var bs []byte
  773. bs, err = xml.Marshal(tagging)
  774. if err != nil {
  775. return err
  776. }
  777. buffer := new(bytes.Buffer)
  778. buffer.Write(bs)
  779. contentType := http.DetectContentType(buffer.Bytes())
  780. headers := map[string]string{}
  781. headers[HTTPHeaderContentType] = contentType
  782. params := map[string]interface{}{}
  783. params["tagging"] = nil
  784. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  785. if err != nil {
  786. return err
  787. }
  788. defer resp.Body.Close()
  789. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  790. }
  791. // GetBucketTagging get tagging of the bucket
  792. // bucketName name of bucket
  793. // error nil if success, otherwise error
  794. func (client Client) GetBucketTagging(bucketName string, options ...Option) (GetBucketTaggingResult, error) {
  795. var out GetBucketTaggingResult
  796. params := map[string]interface{}{}
  797. params["tagging"] = nil
  798. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  799. if err != nil {
  800. return out, err
  801. }
  802. defer resp.Body.Close()
  803. err = xmlUnmarshal(resp.Body, &out)
  804. return out, err
  805. }
  806. //
  807. // DeleteBucketTagging delete bucket tagging
  808. // bucketName name of bucket
  809. // error nil if success, otherwise error
  810. //
  811. func (client Client) DeleteBucketTagging(bucketName string, options ...Option) error {
  812. params := map[string]interface{}{}
  813. params["tagging"] = nil
  814. resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
  815. if err != nil {
  816. return err
  817. }
  818. defer resp.Body.Close()
  819. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  820. }
  821. // GetBucketStat get bucket stat
  822. // bucketName the bucket name.
  823. // error it's nil if no error, otherwise it's an error object.
  824. func (client Client) GetBucketStat(bucketName string) (GetBucketStatResult, error) {
  825. var out GetBucketStatResult
  826. params := map[string]interface{}{}
  827. params["stat"] = nil
  828. resp, err := client.do("GET", bucketName, params, nil, nil)
  829. if err != nil {
  830. return out, err
  831. }
  832. defer resp.Body.Close()
  833. err = xmlUnmarshal(resp.Body, &out)
  834. return out, err
  835. }
  836. // GetBucketPolicy API operation for Object Storage Service.
  837. //
  838. // Get the policy from the bucket.
  839. //
  840. // bucketName the bucket name.
  841. //
  842. // string return the bucket's policy, and it's only valid when error is nil.
  843. //
  844. // error it's nil if no error, otherwise it's an error object.
  845. //
  846. func (client Client) GetBucketPolicy(bucketName string, options ...Option) (string, error) {
  847. params := map[string]interface{}{}
  848. params["policy"] = nil
  849. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  850. if err != nil {
  851. return "", err
  852. }
  853. defer resp.Body.Close()
  854. body, err := ioutil.ReadAll(resp.Body)
  855. out := string(body)
  856. return out, err
  857. }
  858. // SetBucketPolicy API operation for Object Storage Service.
  859. //
  860. // Set the policy from the bucket.
  861. //
  862. // bucketName the bucket name.
  863. //
  864. // policy the bucket policy.
  865. //
  866. // error it's nil if no error, otherwise it's an error object.
  867. //
  868. func (client Client) SetBucketPolicy(bucketName string, policy string, options ...Option) error {
  869. params := map[string]interface{}{}
  870. params["policy"] = nil
  871. buffer := strings.NewReader(policy)
  872. resp, err := client.do("PUT", bucketName, params, nil, buffer, options...)
  873. if err != nil {
  874. return err
  875. }
  876. defer resp.Body.Close()
  877. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  878. }
  879. // DeleteBucketPolicy API operation for Object Storage Service.
  880. //
  881. // Deletes the policy from the bucket.
  882. //
  883. // bucketName the bucket name.
  884. //
  885. // error it's nil if no error, otherwise it's an error object.
  886. //
  887. func (client Client) DeleteBucketPolicy(bucketName string, options ...Option) error {
  888. params := map[string]interface{}{}
  889. params["policy"] = nil
  890. resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
  891. if err != nil {
  892. return err
  893. }
  894. defer resp.Body.Close()
  895. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  896. }
  897. // SetBucketRequestPayment API operation for Object Storage Service.
  898. //
  899. // Set the requestPayment of bucket
  900. //
  901. // bucketName the bucket name.
  902. //
  903. // paymentConfig the payment configuration
  904. //
  905. // error it's nil if no error, otherwise it's an error object.
  906. //
  907. func (client Client) SetBucketRequestPayment(bucketName string, paymentConfig RequestPaymentConfiguration, options ...Option) error {
  908. params := map[string]interface{}{}
  909. params["requestPayment"] = nil
  910. var bs []byte
  911. bs, err := xml.Marshal(paymentConfig)
  912. if err != nil {
  913. return err
  914. }
  915. buffer := new(bytes.Buffer)
  916. buffer.Write(bs)
  917. contentType := http.DetectContentType(buffer.Bytes())
  918. headers := map[string]string{}
  919. headers[HTTPHeaderContentType] = contentType
  920. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  921. if err != nil {
  922. return err
  923. }
  924. defer resp.Body.Close()
  925. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  926. }
  927. // GetBucketRequestPayment API operation for Object Storage Service.
  928. //
  929. // Get bucket requestPayment
  930. //
  931. // bucketName the bucket name.
  932. //
  933. // RequestPaymentConfiguration the payment configuration
  934. //
  935. // error it's nil if no error, otherwise it's an error object.
  936. //
  937. func (client Client) GetBucketRequestPayment(bucketName string, options ...Option) (RequestPaymentConfiguration, error) {
  938. var out RequestPaymentConfiguration
  939. params := map[string]interface{}{}
  940. params["requestPayment"] = nil
  941. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  942. if err != nil {
  943. return out, err
  944. }
  945. defer resp.Body.Close()
  946. err = xmlUnmarshal(resp.Body, &out)
  947. return out, err
  948. }
  949. // GetUserQoSInfo API operation for Object Storage Service.
  950. //
  951. // Get user qos.
  952. //
  953. // UserQoSConfiguration the User Qos and range Information.
  954. //
  955. // error it's nil if no error, otherwise it's an error object.
  956. //
  957. func (client Client) GetUserQoSInfo(options ...Option) (UserQoSConfiguration, error) {
  958. var out UserQoSConfiguration
  959. params := map[string]interface{}{}
  960. params["qosInfo"] = nil
  961. resp, err := client.do("GET", "", params, nil, nil, options...)
  962. if err != nil {
  963. return out, err
  964. }
  965. defer resp.Body.Close()
  966. err = xmlUnmarshal(resp.Body, &out)
  967. return out, err
  968. }
  969. // SetBucketQoSInfo API operation for Object Storage Service.
  970. //
  971. // Set Bucket Qos information.
  972. //
  973. // bucketName tht bucket name.
  974. //
  975. // qosConf the qos configuration.
  976. //
  977. // error it's nil if no error, otherwise it's an error object.
  978. //
  979. func (client Client) SetBucketQoSInfo(bucketName string, qosConf BucketQoSConfiguration, options ...Option) error {
  980. params := map[string]interface{}{}
  981. params["qosInfo"] = nil
  982. var bs []byte
  983. bs, err := xml.Marshal(qosConf)
  984. if err != nil {
  985. return err
  986. }
  987. buffer := new(bytes.Buffer)
  988. buffer.Write(bs)
  989. contentTpye := http.DetectContentType(buffer.Bytes())
  990. headers := map[string]string{}
  991. headers[HTTPHeaderContentType] = contentTpye
  992. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  993. if err != nil {
  994. return err
  995. }
  996. defer resp.Body.Close()
  997. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  998. }
  999. // GetBucketQosInfo API operation for Object Storage Service.
  1000. //
  1001. // Get Bucket Qos information.
  1002. //
  1003. // bucketName tht bucket name.
  1004. //
  1005. // BucketQoSConfiguration the return qos configuration.
  1006. //
  1007. // error it's nil if no error, otherwise it's an error object.
  1008. //
  1009. func (client Client) GetBucketQosInfo(bucketName string, options ...Option) (BucketQoSConfiguration, error) {
  1010. var out BucketQoSConfiguration
  1011. params := map[string]interface{}{}
  1012. params["qosInfo"] = nil
  1013. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  1014. if err != nil {
  1015. return out, err
  1016. }
  1017. defer resp.Body.Close()
  1018. err = xmlUnmarshal(resp.Body, &out)
  1019. return out, err
  1020. }
  1021. // DeleteBucketQosInfo API operation for Object Storage Service.
  1022. //
  1023. // Delete Bucket QoS information.
  1024. //
  1025. // bucketName tht bucket name.
  1026. //
  1027. // error it's nil if no error, otherwise it's an error object.
  1028. //
  1029. func (client Client) DeleteBucketQosInfo(bucketName string, options ...Option) error {
  1030. params := map[string]interface{}{}
  1031. params["qosInfo"] = nil
  1032. resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
  1033. if err != nil {
  1034. return err
  1035. }
  1036. defer resp.Body.Close()
  1037. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  1038. }
  1039. // LimitUploadSpeed set upload bandwidth limit speed,default is 0,unlimited
  1040. // upSpeed KB/s, 0 is unlimited,default is 0
  1041. // error it's nil if success, otherwise failure
  1042. func (client Client) LimitUploadSpeed(upSpeed int) error {
  1043. if client.Config == nil {
  1044. return fmt.Errorf("client config is nil")
  1045. }
  1046. return client.Config.LimitUploadSpeed(upSpeed)
  1047. }
  1048. // UseCname sets the flag of using CName. By default it's false.
  1049. //
  1050. // isUseCname true: the endpoint has the CName, false: the endpoint does not have cname. Default is false.
  1051. //
  1052. func UseCname(isUseCname bool) ClientOption {
  1053. return func(client *Client) {
  1054. client.Config.IsCname = isUseCname
  1055. client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
  1056. }
  1057. }
  1058. // Timeout sets the HTTP timeout in seconds.
  1059. //
  1060. // connectTimeoutSec HTTP timeout in seconds. Default is 10 seconds. 0 means infinite (not recommended)
  1061. // readWriteTimeout HTTP read or write's timeout in seconds. Default is 20 seconds. 0 means infinite.
  1062. //
  1063. func Timeout(connectTimeoutSec, readWriteTimeout int64) ClientOption {
  1064. return func(client *Client) {
  1065. client.Config.HTTPTimeout.ConnectTimeout =
  1066. time.Second * time.Duration(connectTimeoutSec)
  1067. client.Config.HTTPTimeout.ReadWriteTimeout =
  1068. time.Second * time.Duration(readWriteTimeout)
  1069. client.Config.HTTPTimeout.HeaderTimeout =
  1070. time.Second * time.Duration(readWriteTimeout)
  1071. client.Config.HTTPTimeout.IdleConnTimeout =
  1072. time.Second * time.Duration(readWriteTimeout)
  1073. client.Config.HTTPTimeout.LongTimeout =
  1074. time.Second * time.Duration(readWriteTimeout*10)
  1075. }
  1076. }
  1077. // SetBucketInventory API operation for Object Storage Service
  1078. //
  1079. // Set the Bucket inventory.
  1080. //
  1081. // bucketName tht bucket name.
  1082. //
  1083. // inventoryConfig the inventory configuration.
  1084. //
  1085. // error it's nil if no error, otherwise it's an error.
  1086. //
  1087. func (client Client) SetBucketInventory(bucketName string, inventoryConfig InventoryConfiguration, options ...Option) error {
  1088. params := map[string]interface{}{}
  1089. params["inventoryId"] = inventoryConfig.Id
  1090. params["inventory"] = nil
  1091. var bs []byte
  1092. bs, err := xml.Marshal(inventoryConfig)
  1093. if err != nil {
  1094. return err
  1095. }
  1096. buffer := new(bytes.Buffer)
  1097. buffer.Write(bs)
  1098. contentType := http.DetectContentType(buffer.Bytes())
  1099. headers := make(map[string]string)
  1100. headers[HTTPHeaderContentType] = contentType
  1101. resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
  1102. if err != nil {
  1103. return err
  1104. }
  1105. defer resp.Body.Close()
  1106. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  1107. }
  1108. // GetBucketInventory API operation for Object Storage Service
  1109. //
  1110. // Get the Bucket inventory.
  1111. //
  1112. // bucketName tht bucket name.
  1113. //
  1114. // strInventoryId the inventory id.
  1115. //
  1116. // InventoryConfiguration the inventory configuration.
  1117. //
  1118. // error it's nil if no error, otherwise it's an error.
  1119. //
  1120. func (client Client) GetBucketInventory(bucketName string, strInventoryId string, options ...Option) (InventoryConfiguration, error) {
  1121. var out InventoryConfiguration
  1122. params := map[string]interface{}{}
  1123. params["inventory"] = nil
  1124. params["inventoryId"] = strInventoryId
  1125. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  1126. if err != nil {
  1127. return out, err
  1128. }
  1129. defer resp.Body.Close()
  1130. err = xmlUnmarshal(resp.Body, &out)
  1131. return out, err
  1132. }
  1133. // ListBucketInventory API operation for Object Storage Service
  1134. //
  1135. // List the Bucket inventory.
  1136. //
  1137. // bucketName tht bucket name.
  1138. //
  1139. // continuationToken the users token.
  1140. //
  1141. // ListInventoryConfigurationsResult list all inventory configuration by .
  1142. //
  1143. // error it's nil if no error, otherwise it's an error.
  1144. //
  1145. func (client Client) ListBucketInventory(bucketName, continuationToken string, options ...Option) (ListInventoryConfigurationsResult, error) {
  1146. var out ListInventoryConfigurationsResult
  1147. params := map[string]interface{}{}
  1148. params["inventory"] = nil
  1149. if continuationToken == "" {
  1150. params["continuation-token"] = nil
  1151. } else {
  1152. params["continuation-token"] = continuationToken
  1153. }
  1154. resp, err := client.do("GET", bucketName, params, nil, nil, options...)
  1155. if err != nil {
  1156. return out, err
  1157. }
  1158. defer resp.Body.Close()
  1159. err = xmlUnmarshal(resp.Body, &out)
  1160. return out, err
  1161. }
  1162. // DeleteBucketInventory API operation for Object Storage Service.
  1163. //
  1164. // Delete Bucket inventory information.
  1165. //
  1166. // bucketName tht bucket name.
  1167. //
  1168. // strInventoryId the inventory id.
  1169. //
  1170. // error it's nil if no error, otherwise it's an error.
  1171. //
  1172. func (client Client) DeleteBucketInventory(bucketName, strInventoryId string, options ...Option) error {
  1173. params := map[string]interface{}{}
  1174. params["inventory"] = nil
  1175. params["inventoryId"] = strInventoryId
  1176. resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
  1177. if err != nil {
  1178. return err
  1179. }
  1180. defer resp.Body.Close()
  1181. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  1182. }
  1183. // SecurityToken sets the temporary user's SecurityToken.
  1184. //
  1185. // token STS token
  1186. //
  1187. func SecurityToken(token string) ClientOption {
  1188. return func(client *Client) {
  1189. client.Config.SecurityToken = strings.TrimSpace(token)
  1190. }
  1191. }
  1192. // EnableMD5 enables MD5 validation.
  1193. //
  1194. // isEnableMD5 true: enable MD5 validation; false: disable MD5 validation.
  1195. //
  1196. func EnableMD5(isEnableMD5 bool) ClientOption {
  1197. return func(client *Client) {
  1198. client.Config.IsEnableMD5 = isEnableMD5
  1199. }
  1200. }
  1201. // MD5ThresholdCalcInMemory sets the memory usage threshold for computing the MD5, default is 16MB.
  1202. //
  1203. // threshold the memory threshold in bytes. When the uploaded content is more than 16MB, the temp file is used for computing the MD5.
  1204. //
  1205. func MD5ThresholdCalcInMemory(threshold int64) ClientOption {
  1206. return func(client *Client) {
  1207. client.Config.MD5Threshold = threshold
  1208. }
  1209. }
  1210. // EnableCRC enables the CRC checksum. Default is true.
  1211. //
  1212. // isEnableCRC true: enable CRC checksum; false: disable the CRC checksum.
  1213. //
  1214. func EnableCRC(isEnableCRC bool) ClientOption {
  1215. return func(client *Client) {
  1216. client.Config.IsEnableCRC = isEnableCRC
  1217. }
  1218. }
  1219. // UserAgent specifies UserAgent. The default is aliyun-sdk-go/1.2.0 (windows/-/amd64;go1.5.2).
  1220. //
  1221. // userAgent the user agent string.
  1222. //
  1223. func UserAgent(userAgent string) ClientOption {
  1224. return func(client *Client) {
  1225. client.Config.UserAgent = userAgent
  1226. }
  1227. }
  1228. // Proxy sets the proxy (optional). The default is not using proxy.
  1229. //
  1230. // proxyHost the proxy host in the format "host:port". For example, proxy.com:80 .
  1231. //
  1232. func Proxy(proxyHost string) ClientOption {
  1233. return func(client *Client) {
  1234. client.Config.IsUseProxy = true
  1235. client.Config.ProxyHost = proxyHost
  1236. client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
  1237. }
  1238. }
  1239. // AuthProxy sets the proxy information with user name and password.
  1240. //
  1241. // proxyHost the proxy host in the format "host:port". For example, proxy.com:80 .
  1242. // proxyUser the proxy user name.
  1243. // proxyPassword the proxy password.
  1244. //
  1245. func AuthProxy(proxyHost, proxyUser, proxyPassword string) ClientOption {
  1246. return func(client *Client) {
  1247. client.Config.IsUseProxy = true
  1248. client.Config.ProxyHost = proxyHost
  1249. client.Config.IsAuthProxy = true
  1250. client.Config.ProxyUser = proxyUser
  1251. client.Config.ProxyPassword = proxyPassword
  1252. client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
  1253. }
  1254. }
  1255. //
  1256. // HTTPClient sets the http.Client in use to the one passed in
  1257. //
  1258. func HTTPClient(HTTPClient *http.Client) ClientOption {
  1259. return func(client *Client) {
  1260. client.HTTPClient = HTTPClient
  1261. }
  1262. }
  1263. //
  1264. // SetLogLevel sets the oss sdk log level
  1265. //
  1266. func SetLogLevel(LogLevel int) ClientOption {
  1267. return func(client *Client) {
  1268. client.Config.LogLevel = LogLevel
  1269. }
  1270. }
  1271. //
  1272. // SetLogger sets the oss sdk logger
  1273. //
  1274. func SetLogger(Logger *log.Logger) ClientOption {
  1275. return func(client *Client) {
  1276. client.Config.Logger = Logger
  1277. }
  1278. }
  1279. // SetCredentialsProvider sets funciton for get the user's ak
  1280. func SetCredentialsProvider(provider CredentialsProvider) ClientOption {
  1281. return func(client *Client) {
  1282. client.Config.CredentialsProvider = provider
  1283. }
  1284. }
  1285. // SetLocalAddr sets funciton for local addr
  1286. func SetLocalAddr(localAddr net.Addr) ClientOption {
  1287. return func(client *Client) {
  1288. client.Config.LocalAddr = localAddr
  1289. }
  1290. }
  1291. // AuthVersion sets auth version: v1 or v2 signature which oss_server needed
  1292. func AuthVersion(authVersion AuthVersionType) ClientOption {
  1293. return func(client *Client) {
  1294. client.Config.AuthVersion = authVersion
  1295. }
  1296. }
  1297. // AdditionalHeaders sets special http headers needed to be signed
  1298. func AdditionalHeaders(headers []string) ClientOption {
  1299. return func(client *Client) {
  1300. client.Config.AdditionalHeaders = headers
  1301. }
  1302. }
  1303. // Private
  1304. func (client Client) do(method, bucketName string, params map[string]interface{},
  1305. headers map[string]string, data io.Reader, options ...Option) (*Response, error) {
  1306. err := CheckBucketName(bucketName)
  1307. if len(bucketName) > 0 && err != nil {
  1308. return nil, err
  1309. }
  1310. resp, err := client.Conn.Do(method, bucketName, "", params, headers, data, 0, nil)
  1311. // get response header
  1312. respHeader, _ := findOption(options, responseHeader, nil)
  1313. if respHeader != nil {
  1314. pRespHeader := respHeader.(*http.Header)
  1315. *pRespHeader = resp.Headers
  1316. }
  1317. return resp, err
  1318. }