client.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  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. "log"
  10. "net/http"
  11. "strings"
  12. "time"
  13. )
  14. // 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).
  15. // Object related operations are done by Bucket class.
  16. // Users use oss.New to create Client instance.
  17. //
  18. type (
  19. // Client OSS client
  20. Client struct {
  21. Config *Config // OSS client configuration
  22. Conn *Conn // Send HTTP request
  23. HTTPClient *http.Client //http.Client to use - if nil will make its own
  24. }
  25. // ClientOption client option such as UseCname, Timeout, SecurityToken.
  26. ClientOption func(*Client)
  27. )
  28. // New creates a new client.
  29. //
  30. // endpoint the OSS datacenter endpoint such as http://oss-cn-hangzhou.aliyuncs.com .
  31. // accessKeyId access key Id.
  32. // accessKeySecret access key secret.
  33. //
  34. // Client creates the new client instance, the returned value is valid when error is nil.
  35. // error it's nil if no error, otherwise it's an error object.
  36. //
  37. func New(endpoint, accessKeyID, accessKeySecret string, options ...ClientOption) (*Client, error) {
  38. // Configuration
  39. config := getDefaultOssConfig()
  40. config.Endpoint = endpoint
  41. config.AccessKeyID = accessKeyID
  42. config.AccessKeySecret = accessKeySecret
  43. // URL parse
  44. url := &urlMaker{}
  45. url.Init(config.Endpoint, config.IsCname, config.IsUseProxy)
  46. // HTTP connect
  47. conn := &Conn{config: config, url: url}
  48. // OSS client
  49. client := &Client{
  50. Config: config,
  51. Conn: conn,
  52. }
  53. // Client options parse
  54. for _, option := range options {
  55. option(client)
  56. }
  57. // Create HTTP connection
  58. err := conn.init(config, url, client.HTTPClient)
  59. return client, err
  60. }
  61. // Bucket gets the bucket instance.
  62. //
  63. // bucketName the bucket name.
  64. // Bucket the bucket object, when error is nil.
  65. //
  66. // error it's nil if no error, otherwise it's an error object.
  67. //
  68. func (client Client) Bucket(bucketName string) (*Bucket, error) {
  69. return &Bucket{
  70. client,
  71. bucketName,
  72. }, nil
  73. }
  74. // CreateBucket creates a bucket.
  75. //
  76. // bucketName the bucket name, it's globably unique and immutable. The bucket name can only consist of lowercase letters, numbers and dash ('-').
  77. // It must start with lowercase letter or number and the length can only be between 3 and 255.
  78. // options options for creating the bucket, with optional ACL. The ACL could be ACLPrivate, ACLPublicRead, and ACLPublicReadWrite. By default it's ACLPrivate.
  79. // It could also be specified with StorageClass option, which supports StorageStandard, StorageIA(infrequent access), StorageArchive.
  80. //
  81. // error it's nil if no error, otherwise it's an error object.
  82. //
  83. func (client Client) CreateBucket(bucketName string, options ...Option) error {
  84. headers := make(map[string]string)
  85. handleOptions(headers, options)
  86. buffer := new(bytes.Buffer)
  87. isOptSet, val, _ := isOptionSet(options, storageClass)
  88. if isOptSet {
  89. cbConfig := createBucketConfiguration{StorageClass: val.(StorageClassType)}
  90. bs, err := xml.Marshal(cbConfig)
  91. if err != nil {
  92. return err
  93. }
  94. buffer.Write(bs)
  95. contentType := http.DetectContentType(buffer.Bytes())
  96. headers[HTTPHeaderContentType] = contentType
  97. }
  98. params := map[string]interface{}{}
  99. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  100. if err != nil {
  101. return err
  102. }
  103. defer resp.Body.Close()
  104. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  105. }
  106. // ListBuckets lists buckets of the current account under the given endpoint, with optional filters.
  107. //
  108. // options specifies the filters such as Prefix, Marker and MaxKeys. Prefix is the bucket name's prefix filter.
  109. // And marker makes sure the returned buckets' name are greater than it in lexicographic order.
  110. // Maxkeys limits the max keys to return, and by default it's 100 and up to 1000.
  111. // For the common usage scenario, please check out list_bucket.go in the sample.
  112. // ListBucketsResponse the response object if error is nil.
  113. //
  114. // error it's nil if no error, otherwise it's an error object.
  115. //
  116. func (client Client) ListBuckets(options ...Option) (ListBucketsResult, error) {
  117. var out ListBucketsResult
  118. params, err := getRawParams(options)
  119. if err != nil {
  120. return out, err
  121. }
  122. resp, err := client.do("GET", "", params, nil, nil)
  123. if err != nil {
  124. return out, err
  125. }
  126. defer resp.Body.Close()
  127. err = xmlUnmarshal(resp.Body, &out)
  128. return out, err
  129. }
  130. // IsBucketExist checks if the bucket exists
  131. //
  132. // bucketName the bucket name.
  133. //
  134. // bool true if it exists, and it's only valid when error is nil.
  135. // error it's nil if no error, otherwise it's an error object.
  136. //
  137. func (client Client) IsBucketExist(bucketName string) (bool, error) {
  138. listRes, err := client.ListBuckets(Prefix(bucketName), MaxKeys(1))
  139. if err != nil {
  140. return false, err
  141. }
  142. if len(listRes.Buckets) == 1 && listRes.Buckets[0].Name == bucketName {
  143. return true, nil
  144. }
  145. return false, nil
  146. }
  147. // DeleteBucket deletes the bucket. Only empty bucket can be deleted (no object and parts).
  148. //
  149. // bucketName the bucket name.
  150. //
  151. // error it's nil if no error, otherwise it's an error object.
  152. //
  153. func (client Client) DeleteBucket(bucketName string) error {
  154. params := map[string]interface{}{}
  155. resp, err := client.do("DELETE", bucketName, params, nil, nil)
  156. if err != nil {
  157. return err
  158. }
  159. defer resp.Body.Close()
  160. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  161. }
  162. // GetBucketLocation gets the bucket location.
  163. //
  164. // Checks out the following link for more information :
  165. // https://help.aliyun.com/document_detail/oss/user_guide/oss_concept/endpoint.html
  166. //
  167. // bucketName the bucket name
  168. //
  169. // string bucket's datacenter location
  170. // error it's nil if no error, otherwise it's an error object.
  171. //
  172. func (client Client) GetBucketLocation(bucketName string) (string, error) {
  173. params := map[string]interface{}{}
  174. params["location"] = nil
  175. resp, err := client.do("GET", bucketName, params, nil, nil)
  176. if err != nil {
  177. return "", err
  178. }
  179. defer resp.Body.Close()
  180. var LocationConstraint string
  181. err = xmlUnmarshal(resp.Body, &LocationConstraint)
  182. return LocationConstraint, err
  183. }
  184. // SetBucketACL sets bucket's ACL.
  185. //
  186. // bucketName the bucket name
  187. // bucketAcl the bucket ACL: ACLPrivate, ACLPublicRead and ACLPublicReadWrite.
  188. //
  189. // error it's nil if no error, otherwise it's an error object.
  190. //
  191. func (client Client) SetBucketACL(bucketName string, bucketACL ACLType) error {
  192. headers := map[string]string{HTTPHeaderOssACL: string(bucketACL)}
  193. params := map[string]interface{}{}
  194. resp, err := client.do("PUT", bucketName, params, headers, nil)
  195. if err != nil {
  196. return err
  197. }
  198. defer resp.Body.Close()
  199. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  200. }
  201. // GetBucketACL gets the bucket ACL.
  202. //
  203. // bucketName the bucket name.
  204. //
  205. // GetBucketAclResponse the result object, and it's only valid when error is nil.
  206. // error it's nil if no error, otherwise it's an error object.
  207. //
  208. func (client Client) GetBucketACL(bucketName string) (GetBucketACLResult, error) {
  209. var out GetBucketACLResult
  210. params := map[string]interface{}{}
  211. params["acl"] = nil
  212. resp, err := client.do("GET", bucketName, params, nil, nil)
  213. if err != nil {
  214. return out, err
  215. }
  216. defer resp.Body.Close()
  217. err = xmlUnmarshal(resp.Body, &out)
  218. return out, err
  219. }
  220. // SetBucketLifecycle sets the bucket's lifecycle.
  221. //
  222. // For more information, checks out following link:
  223. // https://help.aliyun.com/document_detail/oss/user_guide/manage_object/object_lifecycle.html
  224. //
  225. // bucketName the bucket name.
  226. // rules the lifecycle rules. There're two kind of rules: absolute time expiration and relative time expiration in days and day/month/year respectively.
  227. // Check out sample/bucket_lifecycle.go for more details.
  228. //
  229. // error it's nil if no error, otherwise it's an error object.
  230. //
  231. func (client Client) SetBucketLifecycle(bucketName string, rules []LifecycleRule) error {
  232. lxml := lifecycleXML{Rules: convLifecycleRule(rules)}
  233. bs, err := xml.Marshal(lxml)
  234. if err != nil {
  235. return err
  236. }
  237. buffer := new(bytes.Buffer)
  238. buffer.Write(bs)
  239. contentType := http.DetectContentType(buffer.Bytes())
  240. headers := map[string]string{}
  241. headers[HTTPHeaderContentType] = contentType
  242. params := map[string]interface{}{}
  243. params["lifecycle"] = nil
  244. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  245. if err != nil {
  246. return err
  247. }
  248. defer resp.Body.Close()
  249. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  250. }
  251. // DeleteBucketLifecycle deletes the bucket's lifecycle.
  252. //
  253. //
  254. // bucketName the bucket name.
  255. //
  256. // error it's nil if no error, otherwise it's an error object.
  257. //
  258. func (client Client) DeleteBucketLifecycle(bucketName string) error {
  259. params := map[string]interface{}{}
  260. params["lifecycle"] = nil
  261. resp, err := client.do("DELETE", bucketName, params, nil, nil)
  262. if err != nil {
  263. return err
  264. }
  265. defer resp.Body.Close()
  266. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  267. }
  268. // GetBucketLifecycle gets the bucket's lifecycle settings.
  269. //
  270. // bucketName the bucket name.
  271. //
  272. // GetBucketLifecycleResponse the result object upon successful request. It's only valid when error is nil.
  273. // error it's nil if no error, otherwise it's an error object.
  274. //
  275. func (client Client) GetBucketLifecycle(bucketName string) (GetBucketLifecycleResult, error) {
  276. var out GetBucketLifecycleResult
  277. params := map[string]interface{}{}
  278. params["lifecycle"] = nil
  279. resp, err := client.do("GET", bucketName, params, nil, nil)
  280. if err != nil {
  281. return out, err
  282. }
  283. defer resp.Body.Close()
  284. err = xmlUnmarshal(resp.Body, &out)
  285. return out, err
  286. }
  287. // SetBucketReferer sets the bucket's referer whitelist and the flag if allowing empty referrer.
  288. //
  289. // 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
  290. // the allowing empty referrer flag. Note that this applies to requests from webbrowser only.
  291. // For example, for a bucket os-example and its referrer http://www.aliyun.com, all requests from this URL could access the bucket.
  292. // For more information, please check out this link :
  293. // https://help.aliyun.com/document_detail/oss/user_guide/security_management/referer.html
  294. //
  295. // bucketName the bucket name.
  296. // referers the referrer white list. A bucket could have a referrer list and each referrer supports one '*' and multiple '?' as wildcards.
  297. // The sample could be found in sample/bucket_referer.go
  298. // allowEmptyReferer the flag of allowing empty referrer. By default it's true.
  299. //
  300. // error it's nil if no error, otherwise it's an error object.
  301. //
  302. func (client Client) SetBucketReferer(bucketName string, referers []string, allowEmptyReferer bool) error {
  303. rxml := RefererXML{}
  304. rxml.AllowEmptyReferer = allowEmptyReferer
  305. if referers == nil {
  306. rxml.RefererList = append(rxml.RefererList, "")
  307. } else {
  308. for _, referer := range referers {
  309. rxml.RefererList = append(rxml.RefererList, referer)
  310. }
  311. }
  312. bs, err := xml.Marshal(rxml)
  313. if err != nil {
  314. return err
  315. }
  316. buffer := new(bytes.Buffer)
  317. buffer.Write(bs)
  318. contentType := http.DetectContentType(buffer.Bytes())
  319. headers := map[string]string{}
  320. headers[HTTPHeaderContentType] = contentType
  321. params := map[string]interface{}{}
  322. params["referer"] = nil
  323. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  324. if err != nil {
  325. return err
  326. }
  327. defer resp.Body.Close()
  328. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  329. }
  330. // GetBucketReferer gets the bucket's referrer white list.
  331. //
  332. // bucketName the bucket name.
  333. //
  334. // GetBucketRefererResponse the result object upon successful request. It's only valid when error is nil.
  335. // error it's nil if no error, otherwise it's an error object.
  336. //
  337. func (client Client) GetBucketReferer(bucketName string) (GetBucketRefererResult, error) {
  338. var out GetBucketRefererResult
  339. params := map[string]interface{}{}
  340. params["referer"] = nil
  341. resp, err := client.do("GET", bucketName, params, nil, nil)
  342. if err != nil {
  343. return out, err
  344. }
  345. defer resp.Body.Close()
  346. err = xmlUnmarshal(resp.Body, &out)
  347. return out, err
  348. }
  349. // SetBucketLogging sets the bucket logging settings.
  350. //
  351. // OSS could automatically store the access log. Only the bucket owner could enable the logging.
  352. // Once enabled, OSS would save all the access log into hourly log files in a specified bucket.
  353. // For more information, please check out https://help.aliyun.com/document_detail/oss/user_guide/security_management/logging.html
  354. //
  355. // bucketName bucket name to enable the log.
  356. // targetBucket the target bucket name to store the log files.
  357. // targetPrefix the log files' prefix.
  358. //
  359. // error it's nil if no error, otherwise it's an error object.
  360. //
  361. func (client Client) SetBucketLogging(bucketName, targetBucket, targetPrefix string,
  362. isEnable bool) error {
  363. var err error
  364. var bs []byte
  365. if isEnable {
  366. lxml := LoggingXML{}
  367. lxml.LoggingEnabled.TargetBucket = targetBucket
  368. lxml.LoggingEnabled.TargetPrefix = targetPrefix
  369. bs, err = xml.Marshal(lxml)
  370. } else {
  371. lxml := loggingXMLEmpty{}
  372. bs, err = xml.Marshal(lxml)
  373. }
  374. if err != nil {
  375. return err
  376. }
  377. buffer := new(bytes.Buffer)
  378. buffer.Write(bs)
  379. contentType := http.DetectContentType(buffer.Bytes())
  380. headers := map[string]string{}
  381. headers[HTTPHeaderContentType] = contentType
  382. params := map[string]interface{}{}
  383. params["logging"] = nil
  384. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  385. if err != nil {
  386. return err
  387. }
  388. defer resp.Body.Close()
  389. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  390. }
  391. // DeleteBucketLogging deletes the logging configuration to disable the logging on the bucket.
  392. //
  393. // bucketName the bucket name to disable the logging.
  394. //
  395. // error it's nil if no error, otherwise it's an error object.
  396. //
  397. func (client Client) DeleteBucketLogging(bucketName string) error {
  398. params := map[string]interface{}{}
  399. params["logging"] = nil
  400. resp, err := client.do("DELETE", bucketName, params, nil, nil)
  401. if err != nil {
  402. return err
  403. }
  404. defer resp.Body.Close()
  405. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  406. }
  407. // GetBucketLogging gets the bucket's logging settings
  408. //
  409. // bucketName the bucket name
  410. // GetBucketLoggingResponse the result object upon successful request. It's only valid when error is nil.
  411. //
  412. // error it's nil if no error, otherwise it's an error object.
  413. //
  414. func (client Client) GetBucketLogging(bucketName string) (GetBucketLoggingResult, error) {
  415. var out GetBucketLoggingResult
  416. params := map[string]interface{}{}
  417. params["logging"] = nil
  418. resp, err := client.do("GET", bucketName, params, nil, nil)
  419. if err != nil {
  420. return out, err
  421. }
  422. defer resp.Body.Close()
  423. err = xmlUnmarshal(resp.Body, &out)
  424. return out, err
  425. }
  426. // SetBucketWebsite sets the bucket's static website's index and error page.
  427. //
  428. // 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.
  429. // For more information, please check out: https://help.aliyun.com/document_detail/oss/user_guide/static_host_website.html
  430. //
  431. // bucketName the bucket name to enable static web site.
  432. // indexDocument index page.
  433. // errorDocument error page.
  434. //
  435. // error it's nil if no error, otherwise it's an error object.
  436. //
  437. func (client Client) SetBucketWebsite(bucketName, indexDocument, errorDocument string) error {
  438. wxml := WebsiteXML{}
  439. wxml.IndexDocument.Suffix = indexDocument
  440. wxml.ErrorDocument.Key = errorDocument
  441. bs, err := xml.Marshal(wxml)
  442. if err != nil {
  443. return err
  444. }
  445. buffer := new(bytes.Buffer)
  446. buffer.Write(bs)
  447. contentType := http.DetectContentType(buffer.Bytes())
  448. headers := make(map[string]string)
  449. headers[HTTPHeaderContentType] = contentType
  450. params := map[string]interface{}{}
  451. params["website"] = nil
  452. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  453. if err != nil {
  454. return err
  455. }
  456. defer resp.Body.Close()
  457. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  458. }
  459. // DeleteBucketWebsite deletes the bucket's static web site settings.
  460. //
  461. // bucketName the bucket name.
  462. //
  463. // error it's nil if no error, otherwise it's an error object.
  464. //
  465. func (client Client) DeleteBucketWebsite(bucketName string) error {
  466. params := map[string]interface{}{}
  467. params["website"] = nil
  468. resp, err := client.do("DELETE", bucketName, params, nil, nil)
  469. if err != nil {
  470. return err
  471. }
  472. defer resp.Body.Close()
  473. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  474. }
  475. // GetBucketWebsite gets the bucket's default page (index page) and the error page.
  476. //
  477. // bucketName the bucket name
  478. //
  479. // GetBucketWebsiteResponse the result object upon successful request. It's only valid when error is nil.
  480. // error it's nil if no error, otherwise it's an error object.
  481. //
  482. func (client Client) GetBucketWebsite(bucketName string) (GetBucketWebsiteResult, error) {
  483. var out GetBucketWebsiteResult
  484. params := map[string]interface{}{}
  485. params["website"] = nil
  486. resp, err := client.do("GET", bucketName, params, nil, nil)
  487. if err != nil {
  488. return out, err
  489. }
  490. defer resp.Body.Close()
  491. err = xmlUnmarshal(resp.Body, &out)
  492. return out, err
  493. }
  494. // SetBucketCORS sets the bucket's CORS rules
  495. //
  496. // For more information, please check out https://help.aliyun.com/document_detail/oss/user_guide/security_management/cors.html
  497. //
  498. // bucketName the bucket name
  499. // corsRules the CORS rules to set. The related sample code is in sample/bucket_cors.go.
  500. //
  501. // error it's nil if no error, otherwise it's an error object.
  502. //
  503. func (client Client) SetBucketCORS(bucketName string, corsRules []CORSRule) error {
  504. corsxml := CORSXML{}
  505. for _, v := range corsRules {
  506. cr := CORSRule{}
  507. cr.AllowedMethod = v.AllowedMethod
  508. cr.AllowedOrigin = v.AllowedOrigin
  509. cr.AllowedHeader = v.AllowedHeader
  510. cr.ExposeHeader = v.ExposeHeader
  511. cr.MaxAgeSeconds = v.MaxAgeSeconds
  512. corsxml.CORSRules = append(corsxml.CORSRules, cr)
  513. }
  514. bs, err := xml.Marshal(corsxml)
  515. if err != nil {
  516. return err
  517. }
  518. buffer := new(bytes.Buffer)
  519. buffer.Write(bs)
  520. contentType := http.DetectContentType(buffer.Bytes())
  521. headers := map[string]string{}
  522. headers[HTTPHeaderContentType] = contentType
  523. params := map[string]interface{}{}
  524. params["cors"] = nil
  525. resp, err := client.do("PUT", bucketName, params, headers, buffer)
  526. if err != nil {
  527. return err
  528. }
  529. defer resp.Body.Close()
  530. return checkRespCode(resp.StatusCode, []int{http.StatusOK})
  531. }
  532. // DeleteBucketCORS deletes the bucket's static website settings.
  533. //
  534. // bucketName the bucket name.
  535. //
  536. // error it's nil if no error, otherwise it's an error object.
  537. //
  538. func (client Client) DeleteBucketCORS(bucketName string) error {
  539. params := map[string]interface{}{}
  540. params["cors"] = nil
  541. resp, err := client.do("DELETE", bucketName, params, nil, nil)
  542. if err != nil {
  543. return err
  544. }
  545. defer resp.Body.Close()
  546. return checkRespCode(resp.StatusCode, []int{http.StatusNoContent})
  547. }
  548. // GetBucketCORS gets the bucket's CORS settings.
  549. //
  550. // bucketName the bucket name.
  551. // GetBucketCORSResult the result object upon successful request. It's only valid when error is nil.
  552. //
  553. // error it's nil if no error, otherwise it's an error object.
  554. //
  555. func (client Client) GetBucketCORS(bucketName string) (GetBucketCORSResult, error) {
  556. var out GetBucketCORSResult
  557. params := map[string]interface{}{}
  558. params["cors"] = nil
  559. resp, err := client.do("GET", bucketName, params, nil, nil)
  560. if err != nil {
  561. return out, err
  562. }
  563. defer resp.Body.Close()
  564. err = xmlUnmarshal(resp.Body, &out)
  565. return out, err
  566. }
  567. // GetBucketInfo gets the bucket information.
  568. //
  569. // bucketName the bucket name.
  570. // GetBucketInfoResult the result object upon successful request. It's only valid when error is nil.
  571. //
  572. // error it's nil if no error, otherwise it's an error object.
  573. //
  574. func (client Client) GetBucketInfo(bucketName string) (GetBucketInfoResult, error) {
  575. var out GetBucketInfoResult
  576. params := map[string]interface{}{}
  577. params["bucketInfo"] = nil
  578. resp, err := client.do("GET", bucketName, params, nil, nil)
  579. if err != nil {
  580. return out, err
  581. }
  582. defer resp.Body.Close()
  583. err = xmlUnmarshal(resp.Body, &out)
  584. return out, err
  585. }
  586. // LimitUploadSpeed: set upload bandwidth limit speed,default is 0,unlimited
  587. // upSpeed: KB/s, 0 is unlimited,default is 0
  588. // error:it's nil if success, otherwise failure
  589. func (client Client) LimitUploadSpeed(upSpeed int) error {
  590. if client.Config == nil {
  591. return fmt.Errorf("client config is nil")
  592. }
  593. return client.Config.LimitUploadSpeed(upSpeed)
  594. }
  595. // UseCname sets the flag of using CName. By default it's false.
  596. //
  597. // isUseCname true: the endpoint has the CName, false: the endpoint does not have cname. Default is false.
  598. //
  599. func UseCname(isUseCname bool) ClientOption {
  600. return func(client *Client) {
  601. client.Config.IsCname = isUseCname
  602. client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
  603. }
  604. }
  605. // Timeout sets the HTTP timeout in seconds.
  606. //
  607. // connectTimeoutSec HTTP timeout in seconds. Default is 10 seconds. 0 means infinite (not recommended)
  608. // readWriteTimeout HTTP read or write's timeout in seconds. Default is 20 seconds. 0 means infinite.
  609. //
  610. func Timeout(connectTimeoutSec, readWriteTimeout int64) ClientOption {
  611. return func(client *Client) {
  612. client.Config.HTTPTimeout.ConnectTimeout =
  613. time.Second * time.Duration(connectTimeoutSec)
  614. client.Config.HTTPTimeout.ReadWriteTimeout =
  615. time.Second * time.Duration(readWriteTimeout)
  616. client.Config.HTTPTimeout.HeaderTimeout =
  617. time.Second * time.Duration(readWriteTimeout)
  618. client.Config.HTTPTimeout.IdleConnTimeout =
  619. time.Second * time.Duration(readWriteTimeout)
  620. client.Config.HTTPTimeout.LongTimeout =
  621. time.Second * time.Duration(readWriteTimeout*10)
  622. }
  623. }
  624. // SecurityToken sets the temporary user's SecurityToken.
  625. //
  626. // token STS token
  627. //
  628. func SecurityToken(token string) ClientOption {
  629. return func(client *Client) {
  630. client.Config.SecurityToken = strings.TrimSpace(token)
  631. }
  632. }
  633. // EnableMD5 enables MD5 validation.
  634. //
  635. // isEnableMD5 true: enable MD5 validation; false: disable MD5 validation.
  636. //
  637. func EnableMD5(isEnableMD5 bool) ClientOption {
  638. return func(client *Client) {
  639. client.Config.IsEnableMD5 = isEnableMD5
  640. }
  641. }
  642. // MD5ThresholdCalcInMemory sets the memory usage threshold for computing the MD5, default is 16MB.
  643. //
  644. // threshold the memory threshold in bytes. When the uploaded content is more than 16MB, the temp file is used for computing the MD5.
  645. //
  646. func MD5ThresholdCalcInMemory(threshold int64) ClientOption {
  647. return func(client *Client) {
  648. client.Config.MD5Threshold = threshold
  649. }
  650. }
  651. // EnableCRC enables the CRC checksum. Default is true.
  652. //
  653. // isEnableCRC true: enable CRC checksum; false: disable the CRC checksum.
  654. //
  655. func EnableCRC(isEnableCRC bool) ClientOption {
  656. return func(client *Client) {
  657. client.Config.IsEnableCRC = isEnableCRC
  658. }
  659. }
  660. // UserAgent specifies UserAgent. The default is aliyun-sdk-go/1.2.0 (windows/-/amd64;go1.5.2).
  661. //
  662. // userAgent the user agent string.
  663. //
  664. func UserAgent(userAgent string) ClientOption {
  665. return func(client *Client) {
  666. client.Config.UserAgent = userAgent
  667. }
  668. }
  669. // Proxy sets the proxy (optional). The default is not using proxy.
  670. //
  671. // proxyHost the proxy host in the format "host:port". For example, proxy.com:80 .
  672. //
  673. func Proxy(proxyHost string) ClientOption {
  674. return func(client *Client) {
  675. client.Config.IsUseProxy = true
  676. client.Config.ProxyHost = proxyHost
  677. client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
  678. }
  679. }
  680. // AuthProxy sets the proxy information with user name and password.
  681. //
  682. // proxyHost the proxy host in the format "host:port". For example, proxy.com:80 .
  683. // proxyUser the proxy user name.
  684. // proxyPassword the proxy password.
  685. //
  686. func AuthProxy(proxyHost, proxyUser, proxyPassword string) ClientOption {
  687. return func(client *Client) {
  688. client.Config.IsUseProxy = true
  689. client.Config.ProxyHost = proxyHost
  690. client.Config.IsAuthProxy = true
  691. client.Config.ProxyUser = proxyUser
  692. client.Config.ProxyPassword = proxyPassword
  693. client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
  694. }
  695. }
  696. //
  697. // HTTPClient sets the http.Client in use to the one passed in
  698. //
  699. func HTTPClient(HTTPClient *http.Client) ClientOption {
  700. return func(client *Client) {
  701. client.HTTPClient = HTTPClient
  702. }
  703. }
  704. //
  705. // SetLogLevel sets the oss sdk log level
  706. //
  707. func SetLogLevel(LogLevel int) ClientOption {
  708. return func(client *Client) {
  709. client.Config.LogLevel = LogLevel
  710. }
  711. }
  712. //
  713. // SetLogLevel sets the oss sdk log level
  714. //
  715. func SetLogger(Logger *log.Logger) ClientOption {
  716. return func(client *Client) {
  717. client.Config.Logger = Logger
  718. }
  719. }
  720. // Private
  721. func (client Client) do(method, bucketName string, params map[string]interface{},
  722. headers map[string]string, data io.Reader) (*Response, error) {
  723. return client.Conn.Do(method, bucketName, "", params,
  724. headers, data, 0, nil)
  725. }