client.go 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499
  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. client.Config.UserSetUa = true
  1227. }
  1228. }
  1229. // Proxy sets the proxy (optional). The default is not using proxy.
  1230. //
  1231. // proxyHost the proxy host in the format "host:port". For example, proxy.com:80 .
  1232. //
  1233. func Proxy(proxyHost string) ClientOption {
  1234. return func(client *Client) {
  1235. client.Config.IsUseProxy = true
  1236. client.Config.ProxyHost = proxyHost
  1237. client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
  1238. }
  1239. }
  1240. // AuthProxy sets the proxy information with user name and password.
  1241. //
  1242. // proxyHost the proxy host in the format "host:port". For example, proxy.com:80 .
  1243. // proxyUser the proxy user name.
  1244. // proxyPassword the proxy password.
  1245. //
  1246. func AuthProxy(proxyHost, proxyUser, proxyPassword string) ClientOption {
  1247. return func(client *Client) {
  1248. client.Config.IsUseProxy = true
  1249. client.Config.ProxyHost = proxyHost
  1250. client.Config.IsAuthProxy = true
  1251. client.Config.ProxyUser = proxyUser
  1252. client.Config.ProxyPassword = proxyPassword
  1253. client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
  1254. }
  1255. }
  1256. //
  1257. // HTTPClient sets the http.Client in use to the one passed in
  1258. //
  1259. func HTTPClient(HTTPClient *http.Client) ClientOption {
  1260. return func(client *Client) {
  1261. client.HTTPClient = HTTPClient
  1262. }
  1263. }
  1264. //
  1265. // SetLogLevel sets the oss sdk log level
  1266. //
  1267. func SetLogLevel(LogLevel int) ClientOption {
  1268. return func(client *Client) {
  1269. client.Config.LogLevel = LogLevel
  1270. }
  1271. }
  1272. //
  1273. // SetLogger sets the oss sdk logger
  1274. //
  1275. func SetLogger(Logger *log.Logger) ClientOption {
  1276. return func(client *Client) {
  1277. client.Config.Logger = Logger
  1278. }
  1279. }
  1280. // SetCredentialsProvider sets funciton for get the user's ak
  1281. func SetCredentialsProvider(provider CredentialsProvider) ClientOption {
  1282. return func(client *Client) {
  1283. client.Config.CredentialsProvider = provider
  1284. }
  1285. }
  1286. // SetLocalAddr sets funciton for local addr
  1287. func SetLocalAddr(localAddr net.Addr) ClientOption {
  1288. return func(client *Client) {
  1289. client.Config.LocalAddr = localAddr
  1290. }
  1291. }
  1292. // AuthVersion sets auth version: v1 or v2 signature which oss_server needed
  1293. func AuthVersion(authVersion AuthVersionType) ClientOption {
  1294. return func(client *Client) {
  1295. client.Config.AuthVersion = authVersion
  1296. }
  1297. }
  1298. // AdditionalHeaders sets special http headers needed to be signed
  1299. func AdditionalHeaders(headers []string) ClientOption {
  1300. return func(client *Client) {
  1301. client.Config.AdditionalHeaders = headers
  1302. }
  1303. }
  1304. // Private
  1305. func (client Client) do(method, bucketName string, params map[string]interface{},
  1306. headers map[string]string, data io.Reader, options ...Option) (*Response, error) {
  1307. err := CheckBucketName(bucketName)
  1308. if len(bucketName) > 0 && err != nil {
  1309. return nil, err
  1310. }
  1311. resp, err := client.Conn.Do(method, bucketName, "", params, headers, data, 0, nil)
  1312. // get response header
  1313. respHeader, _ := FindOption(options, responseHeader, nil)
  1314. if respHeader != nil {
  1315. pRespHeader := respHeader.(*http.Header)
  1316. *pRespHeader = resp.Headers
  1317. }
  1318. return resp, err
  1319. }