client.go 24 KB

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