client.go 46 KB

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