1 // Package oss implements functions for access oss service.
2 // It has two main struct Client and Bucket.
18 // 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).
19 // Object related operations are done by Bucket class.
20 // Users use oss.New to create Client instance.
25 Config *Config // OSS client configuration
26 Conn *Conn // Send HTTP request
27 HTTPClient *http.Client //http.Client to use - if nil will make its own
30 // ClientOption client option such as UseCname, Timeout, SecurityToken.
31 ClientOption func(*Client)
34 // New creates a new client.
36 // endpoint the OSS datacenter endpoint such as http://oss-cn-hangzhou.aliyuncs.com .
37 // accessKeyId access key Id.
38 // accessKeySecret access key secret.
40 // Client creates the new client instance, the returned value is valid when error is nil.
41 // error it's nil if no error, otherwise it's an error object.
43 func New(endpoint, accessKeyID, accessKeySecret string, options ...ClientOption) (*Client, error) {
45 config := getDefaultOssConfig()
46 config.Endpoint = endpoint
47 config.AccessKeyID = accessKeyID
48 config.AccessKeySecret = accessKeySecret
52 err := url.Init(config.Endpoint, config.IsCname, config.IsUseProxy)
58 conn := &Conn{config: config, url: url}
66 // Client options parse
67 for _, option := range options {
71 if config.AuthVersion != AuthV1 && config.AuthVersion != AuthV2 {
72 return nil, fmt.Errorf("Init client Error, invalid Auth version: %v", config.AuthVersion)
75 // Create HTTP connection
76 err = conn.init(config, url, client.HTTPClient)
81 // Bucket gets the bucket instance.
83 // bucketName the bucket name.
84 // Bucket the bucket object, when error is nil.
86 // error it's nil if no error, otherwise it's an error object.
88 func (client Client) Bucket(bucketName string) (*Bucket, error) {
89 err := CheckBucketName(bucketName)
100 // CreateBucket creates a bucket.
102 // bucketName the bucket name, it's globably unique and immutable. The bucket name can only consist of lowercase letters, numbers and dash ('-').
103 // It must start with lowercase letter or number and the length can only be between 3 and 255.
104 // options options for creating the bucket, with optional ACL. The ACL could be ACLPrivate, ACLPublicRead, and ACLPublicReadWrite. By default it's ACLPrivate.
105 // It could also be specified with StorageClass option, which supports StorageStandard, StorageIA(infrequent access), StorageArchive.
107 // error it's nil if no error, otherwise it's an error object.
109 func (client Client) CreateBucket(bucketName string, options ...Option) error {
110 headers := make(map[string]string)
111 handleOptions(headers, options)
113 buffer := new(bytes.Buffer)
115 var cbConfig createBucketConfiguration
116 cbConfig.StorageClass = StorageStandard
118 isStorageSet, valStroage, _ := IsOptionSet(options, storageClass)
119 isRedundancySet, valRedundancy, _ := IsOptionSet(options, redundancyType)
121 cbConfig.StorageClass = valStroage.(StorageClassType)
125 cbConfig.DataRedundancyType = valRedundancy.(DataRedundancyType)
128 bs, err := xml.Marshal(cbConfig)
133 contentType := http.DetectContentType(buffer.Bytes())
134 headers[HTTPHeaderContentType] = contentType
136 params := map[string]interface{}{}
137 resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
142 defer resp.Body.Close()
143 return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
146 // ListBuckets lists buckets of the current account under the given endpoint, with optional filters.
148 // options specifies the filters such as Prefix, Marker and MaxKeys. Prefix is the bucket name's prefix filter.
149 // And marker makes sure the returned buckets' name are greater than it in lexicographic order.
150 // Maxkeys limits the max keys to return, and by default it's 100 and up to 1000.
151 // For the common usage scenario, please check out list_bucket.go in the sample.
152 // ListBucketsResponse the response object if error is nil.
154 // error it's nil if no error, otherwise it's an error object.
156 func (client Client) ListBuckets(options ...Option) (ListBucketsResult, error) {
157 var out ListBucketsResult
159 params, err := GetRawParams(options)
164 resp, err := client.do("GET", "", params, nil, nil, options...)
168 defer resp.Body.Close()
170 err = xmlUnmarshal(resp.Body, &out)
174 // IsBucketExist checks if the bucket exists
176 // bucketName the bucket name.
178 // bool true if it exists, and it's only valid when error is nil.
179 // error it's nil if no error, otherwise it's an error object.
181 func (client Client) IsBucketExist(bucketName string) (bool, error) {
182 listRes, err := client.ListBuckets(Prefix(bucketName), MaxKeys(1))
187 if len(listRes.Buckets) == 1 && listRes.Buckets[0].Name == bucketName {
193 // DeleteBucket deletes the bucket. Only empty bucket can be deleted (no object and parts).
195 // bucketName the bucket name.
197 // error it's nil if no error, otherwise it's an error object.
199 func (client Client) DeleteBucket(bucketName string, options ...Option) error {
200 params := map[string]interface{}{}
201 resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
206 defer resp.Body.Close()
207 return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
210 // GetBucketLocation gets the bucket location.
212 // Checks out the following link for more information :
213 // https://help.aliyun.com/document_detail/oss/user_guide/oss_concept/endpoint.html
215 // bucketName the bucket name
217 // string bucket's datacenter location
218 // error it's nil if no error, otherwise it's an error object.
220 func (client Client) GetBucketLocation(bucketName string) (string, error) {
221 params := map[string]interface{}{}
222 params["location"] = nil
223 resp, err := client.do("GET", bucketName, params, nil, nil)
227 defer resp.Body.Close()
229 var LocationConstraint string
230 err = xmlUnmarshal(resp.Body, &LocationConstraint)
231 return LocationConstraint, err
234 // SetBucketACL sets bucket's ACL.
236 // bucketName the bucket name
237 // bucketAcl the bucket ACL: ACLPrivate, ACLPublicRead and ACLPublicReadWrite.
239 // error it's nil if no error, otherwise it's an error object.
241 func (client Client) SetBucketACL(bucketName string, bucketACL ACLType) error {
242 headers := map[string]string{HTTPHeaderOssACL: string(bucketACL)}
243 params := map[string]interface{}{}
245 resp, err := client.do("PUT", bucketName, params, headers, nil)
249 defer resp.Body.Close()
250 return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
253 // GetBucketACL gets the bucket ACL.
255 // bucketName the bucket name.
257 // GetBucketAclResponse the result object, and it's only valid when error is nil.
258 // error it's nil if no error, otherwise it's an error object.
260 func (client Client) GetBucketACL(bucketName string) (GetBucketACLResult, error) {
261 var out GetBucketACLResult
262 params := map[string]interface{}{}
264 resp, err := client.do("GET", bucketName, params, nil, nil)
268 defer resp.Body.Close()
270 err = xmlUnmarshal(resp.Body, &out)
274 // SetBucketLifecycle sets the bucket's lifecycle.
276 // For more information, checks out following link:
277 // https://help.aliyun.com/document_detail/oss/user_guide/manage_object/object_lifecycle.html
279 // bucketName the bucket name.
280 // rules the lifecycle rules. There're two kind of rules: absolute time expiration and relative time expiration in days and day/month/year respectively.
281 // Check out sample/bucket_lifecycle.go for more details.
283 // error it's nil if no error, otherwise it's an error object.
285 func (client Client) SetBucketLifecycle(bucketName string, rules []LifecycleRule) error {
286 err := verifyLifecycleRules(rules)
290 lifecycleCfg := LifecycleConfiguration{Rules: rules}
291 bs, err := xml.Marshal(lifecycleCfg)
295 buffer := new(bytes.Buffer)
298 contentType := http.DetectContentType(buffer.Bytes())
299 headers := map[string]string{}
300 headers[HTTPHeaderContentType] = contentType
302 params := map[string]interface{}{}
303 params["lifecycle"] = nil
304 resp, err := client.do("PUT", bucketName, params, headers, buffer)
308 defer resp.Body.Close()
309 return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
312 // DeleteBucketLifecycle deletes the bucket's lifecycle.
315 // bucketName the bucket name.
317 // error it's nil if no error, otherwise it's an error object.
319 func (client Client) DeleteBucketLifecycle(bucketName string) error {
320 params := map[string]interface{}{}
321 params["lifecycle"] = nil
322 resp, err := client.do("DELETE", bucketName, params, nil, nil)
326 defer resp.Body.Close()
327 return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
330 // GetBucketLifecycle gets the bucket's lifecycle settings.
332 // bucketName the bucket name.
334 // GetBucketLifecycleResponse 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.
337 func (client Client) GetBucketLifecycle(bucketName string) (GetBucketLifecycleResult, error) {
338 var out GetBucketLifecycleResult
339 params := map[string]interface{}{}
340 params["lifecycle"] = nil
341 resp, err := client.do("GET", bucketName, params, nil, nil)
345 defer resp.Body.Close()
347 err = xmlUnmarshal(resp.Body, &out)
349 // NonVersionTransition is not suggested to use
350 // to keep compatible
351 for k, rule := range out.Rules {
352 if len(rule.NonVersionTransitions) > 0 {
353 out.Rules[k].NonVersionTransition = &(out.Rules[k].NonVersionTransitions[0])
359 // SetBucketReferer sets the bucket's referer whitelist and the flag if allowing empty referrer.
361 // 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
362 // the allowing empty referrer flag. Note that this applies to requests from webbrowser only.
363 // For example, for a bucket os-example and its referrer http://www.aliyun.com, all requests from this URL could access the bucket.
364 // For more information, please check out this link :
365 // https://help.aliyun.com/document_detail/oss/user_guide/security_management/referer.html
367 // bucketName the bucket name.
368 // referers the referrer white list. A bucket could have a referrer list and each referrer supports one '*' and multiple '?' as wildcards.
369 // The sample could be found in sample/bucket_referer.go
370 // allowEmptyReferer the flag of allowing empty referrer. By default it's true.
372 // error it's nil if no error, otherwise it's an error object.
374 func (client Client) SetBucketReferer(bucketName string, referers []string, allowEmptyReferer bool) error {
376 rxml.AllowEmptyReferer = allowEmptyReferer
378 rxml.RefererList = append(rxml.RefererList, "")
380 for _, referer := range referers {
381 rxml.RefererList = append(rxml.RefererList, referer)
385 bs, err := xml.Marshal(rxml)
389 buffer := new(bytes.Buffer)
392 contentType := http.DetectContentType(buffer.Bytes())
393 headers := map[string]string{}
394 headers[HTTPHeaderContentType] = contentType
396 params := map[string]interface{}{}
397 params["referer"] = nil
398 resp, err := client.do("PUT", bucketName, params, headers, buffer)
402 defer resp.Body.Close()
403 return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
406 // GetBucketReferer gets the bucket's referrer white list.
408 // bucketName the bucket name.
410 // GetBucketRefererResponse the result object upon successful request. It's only valid when error is nil.
411 // error it's nil if no error, otherwise it's an error object.
413 func (client Client) GetBucketReferer(bucketName string) (GetBucketRefererResult, error) {
414 var out GetBucketRefererResult
415 params := map[string]interface{}{}
416 params["referer"] = nil
417 resp, err := client.do("GET", bucketName, params, nil, nil)
421 defer resp.Body.Close()
423 err = xmlUnmarshal(resp.Body, &out)
427 // SetBucketLogging sets the bucket logging settings.
429 // OSS could automatically store the access log. Only the bucket owner could enable the logging.
430 // Once enabled, OSS would save all the access log into hourly log files in a specified bucket.
431 // For more information, please check out https://help.aliyun.com/document_detail/oss/user_guide/security_management/logging.html
433 // bucketName bucket name to enable the log.
434 // targetBucket the target bucket name to store the log files.
435 // targetPrefix the log files' prefix.
437 // error it's nil if no error, otherwise it's an error object.
439 func (client Client) SetBucketLogging(bucketName, targetBucket, targetPrefix string,
440 isEnable bool) error {
445 lxml.LoggingEnabled.TargetBucket = targetBucket
446 lxml.LoggingEnabled.TargetPrefix = targetPrefix
447 bs, err = xml.Marshal(lxml)
449 lxml := loggingXMLEmpty{}
450 bs, err = xml.Marshal(lxml)
457 buffer := new(bytes.Buffer)
460 contentType := http.DetectContentType(buffer.Bytes())
461 headers := map[string]string{}
462 headers[HTTPHeaderContentType] = contentType
464 params := map[string]interface{}{}
465 params["logging"] = nil
466 resp, err := client.do("PUT", bucketName, params, headers, buffer)
470 defer resp.Body.Close()
471 return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
474 // DeleteBucketLogging deletes the logging configuration to disable the logging on the bucket.
476 // bucketName the bucket name to disable the logging.
478 // error it's nil if no error, otherwise it's an error object.
480 func (client Client) DeleteBucketLogging(bucketName string) error {
481 params := map[string]interface{}{}
482 params["logging"] = nil
483 resp, err := client.do("DELETE", bucketName, params, nil, nil)
487 defer resp.Body.Close()
488 return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
491 // GetBucketLogging gets the bucket's logging settings
493 // bucketName the bucket name
494 // GetBucketLoggingResponse the result object upon successful request. It's only valid when error is nil.
496 // error it's nil if no error, otherwise it's an error object.
498 func (client Client) GetBucketLogging(bucketName string) (GetBucketLoggingResult, error) {
499 var out GetBucketLoggingResult
500 params := map[string]interface{}{}
501 params["logging"] = nil
502 resp, err := client.do("GET", bucketName, params, nil, nil)
506 defer resp.Body.Close()
508 err = xmlUnmarshal(resp.Body, &out)
512 // SetBucketWebsite sets the bucket's static website's index and error page.
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
517 // bucketName the bucket name to enable static web site.
518 // indexDocument index page.
519 // errorDocument error page.
521 // error it's nil if no error, otherwise it's an error object.
523 func (client Client) SetBucketWebsite(bucketName, indexDocument, errorDocument string) error {
525 wxml.IndexDocument.Suffix = indexDocument
526 wxml.ErrorDocument.Key = errorDocument
528 bs, err := xml.Marshal(wxml)
532 buffer := new(bytes.Buffer)
535 contentType := http.DetectContentType(buffer.Bytes())
536 headers := make(map[string]string)
537 headers[HTTPHeaderContentType] = contentType
539 params := map[string]interface{}{}
540 params["website"] = nil
541 resp, err := client.do("PUT", bucketName, params, headers, buffer)
545 defer resp.Body.Close()
546 return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
549 // SetBucketWebsiteDetail sets the bucket's static website's detail
551 // 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.
552 // For more information, please check out: https://help.aliyun.com/document_detail/oss/user_guide/static_host_website.html
554 // bucketName the bucket name to enable static web site.
556 // wxml the website's detail
558 // error it's nil if no error, otherwise it's an error object.
560 func (client Client) SetBucketWebsiteDetail(bucketName string, wxml WebsiteXML, options ...Option) error {
561 bs, err := xml.Marshal(wxml)
565 buffer := new(bytes.Buffer)
568 contentType := http.DetectContentType(buffer.Bytes())
569 headers := make(map[string]string)
570 headers[HTTPHeaderContentType] = contentType
572 params := map[string]interface{}{}
573 params["website"] = nil
574 resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
578 defer resp.Body.Close()
579 return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
582 // SetBucketWebsiteXml sets the bucket's static website's rule
584 // 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.
585 // For more information, please check out: https://help.aliyun.com/document_detail/oss/user_guide/static_host_website.html
587 // bucketName the bucket name to enable static web site.
589 // wxml the website's detail
591 // error it's nil if no error, otherwise it's an error object.
593 func (client Client) SetBucketWebsiteXml(bucketName string, webXml string, options ...Option) error {
594 buffer := new(bytes.Buffer)
595 buffer.Write([]byte(webXml))
597 contentType := http.DetectContentType(buffer.Bytes())
598 headers := make(map[string]string)
599 headers[HTTPHeaderContentType] = contentType
601 params := map[string]interface{}{}
602 params["website"] = nil
603 resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
607 defer resp.Body.Close()
608 return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
611 // DeleteBucketWebsite deletes the bucket's static web site settings.
613 // bucketName the bucket name.
615 // error it's nil if no error, otherwise it's an error object.
617 func (client Client) DeleteBucketWebsite(bucketName string) error {
618 params := map[string]interface{}{}
619 params["website"] = nil
620 resp, err := client.do("DELETE", bucketName, params, nil, nil)
624 defer resp.Body.Close()
625 return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
628 // GetBucketWebsite gets the bucket's default page (index page) and the error page.
630 // bucketName the bucket name
632 // GetBucketWebsiteResponse the result object upon successful request. It's only valid when error is nil.
633 // error it's nil if no error, otherwise it's an error object.
635 func (client Client) GetBucketWebsite(bucketName string) (GetBucketWebsiteResult, error) {
636 var out GetBucketWebsiteResult
637 params := map[string]interface{}{}
638 params["website"] = nil
639 resp, err := client.do("GET", bucketName, params, nil, nil)
643 defer resp.Body.Close()
645 err = xmlUnmarshal(resp.Body, &out)
649 // SetBucketCORS sets the bucket's CORS rules
651 // For more information, please check out https://help.aliyun.com/document_detail/oss/user_guide/security_management/cors.html
653 // bucketName the bucket name
654 // corsRules the CORS rules to set. The related sample code is in sample/bucket_cors.go.
656 // error it's nil if no error, otherwise it's an error object.
658 func (client Client) SetBucketCORS(bucketName string, corsRules []CORSRule) error {
660 for _, v := range corsRules {
662 cr.AllowedMethod = v.AllowedMethod
663 cr.AllowedOrigin = v.AllowedOrigin
664 cr.AllowedHeader = v.AllowedHeader
665 cr.ExposeHeader = v.ExposeHeader
666 cr.MaxAgeSeconds = v.MaxAgeSeconds
667 corsxml.CORSRules = append(corsxml.CORSRules, cr)
670 bs, err := xml.Marshal(corsxml)
674 buffer := new(bytes.Buffer)
677 contentType := http.DetectContentType(buffer.Bytes())
678 headers := map[string]string{}
679 headers[HTTPHeaderContentType] = contentType
681 params := map[string]interface{}{}
683 resp, err := client.do("PUT", bucketName, params, headers, buffer)
687 defer resp.Body.Close()
688 return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
691 // DeleteBucketCORS deletes the bucket's static website settings.
693 // bucketName the bucket name.
695 // error it's nil if no error, otherwise it's an error object.
697 func (client Client) DeleteBucketCORS(bucketName string) error {
698 params := map[string]interface{}{}
700 resp, err := client.do("DELETE", bucketName, params, nil, nil)
704 defer resp.Body.Close()
705 return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
708 // GetBucketCORS gets the bucket's CORS settings.
710 // bucketName the bucket name.
711 // GetBucketCORSResult the result object upon successful request. It's only valid when error is nil.
713 // error it's nil if no error, otherwise it's an error object.
715 func (client Client) GetBucketCORS(bucketName string) (GetBucketCORSResult, error) {
716 var out GetBucketCORSResult
717 params := map[string]interface{}{}
719 resp, err := client.do("GET", bucketName, params, nil, nil)
723 defer resp.Body.Close()
725 err = xmlUnmarshal(resp.Body, &out)
729 // GetBucketInfo gets the bucket information.
731 // bucketName the bucket name.
732 // GetBucketInfoResult the result object upon successful request. It's only valid when error is nil.
734 // error it's nil if no error, otherwise it's an error object.
736 func (client Client) GetBucketInfo(bucketName string, options ...Option) (GetBucketInfoResult, error) {
737 var out GetBucketInfoResult
738 params := map[string]interface{}{}
739 params["bucketInfo"] = nil
740 resp, err := client.do("GET", bucketName, params, nil, nil, options...)
744 defer resp.Body.Close()
746 err = xmlUnmarshal(resp.Body, &out)
748 // convert None to ""
750 if out.BucketInfo.SseRule.KMSMasterKeyID == "None" {
751 out.BucketInfo.SseRule.KMSMasterKeyID = ""
754 if out.BucketInfo.SseRule.SSEAlgorithm == "None" {
755 out.BucketInfo.SseRule.SSEAlgorithm = ""
758 if out.BucketInfo.SseRule.KMSDataEncryption == "None" {
759 out.BucketInfo.SseRule.KMSDataEncryption = ""
765 // SetBucketVersioning set bucket versioning:Enabled、Suspended
766 // bucketName the bucket name.
767 // error it's nil if no error, otherwise it's an error object.
768 func (client Client) SetBucketVersioning(bucketName string, versioningConfig VersioningConfig, options ...Option) error {
771 bs, err = xml.Marshal(versioningConfig)
777 buffer := new(bytes.Buffer)
780 contentType := http.DetectContentType(buffer.Bytes())
781 headers := map[string]string{}
782 headers[HTTPHeaderContentType] = contentType
784 params := map[string]interface{}{}
785 params["versioning"] = nil
786 resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
791 defer resp.Body.Close()
792 return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
795 // GetBucketVersioning get bucket versioning status:Enabled、Suspended
796 // bucketName the bucket name.
797 // error it's nil if no error, otherwise it's an error object.
798 func (client Client) GetBucketVersioning(bucketName string, options ...Option) (GetBucketVersioningResult, error) {
799 var out GetBucketVersioningResult
800 params := map[string]interface{}{}
801 params["versioning"] = nil
802 resp, err := client.do("GET", bucketName, params, nil, nil, options...)
807 defer resp.Body.Close()
809 err = xmlUnmarshal(resp.Body, &out)
813 // SetBucketEncryption set bucket encryption config
814 // bucketName the bucket name.
815 // error it's nil if no error, otherwise it's an error object.
816 func (client Client) SetBucketEncryption(bucketName string, encryptionRule ServerEncryptionRule, options ...Option) error {
819 bs, err = xml.Marshal(encryptionRule)
825 buffer := new(bytes.Buffer)
828 contentType := http.DetectContentType(buffer.Bytes())
829 headers := map[string]string{}
830 headers[HTTPHeaderContentType] = contentType
832 params := map[string]interface{}{}
833 params["encryption"] = nil
834 resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
839 defer resp.Body.Close()
840 return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
843 // GetBucketEncryption get bucket encryption
844 // bucketName the bucket name.
845 // error it's nil if no error, otherwise it's an error object.
846 func (client Client) GetBucketEncryption(bucketName string, options ...Option) (GetBucketEncryptionResult, error) {
847 var out GetBucketEncryptionResult
848 params := map[string]interface{}{}
849 params["encryption"] = nil
850 resp, err := client.do("GET", bucketName, params, nil, nil, options...)
855 defer resp.Body.Close()
857 err = xmlUnmarshal(resp.Body, &out)
861 // DeleteBucketEncryption delete bucket encryption config
862 // bucketName the bucket name.
863 // error it's nil if no error, otherwise it's an error bucket
864 func (client Client) DeleteBucketEncryption(bucketName string, options ...Option) error {
865 params := map[string]interface{}{}
866 params["encryption"] = nil
867 resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
872 defer resp.Body.Close()
873 return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
877 // SetBucketTagging add tagging to bucket
878 // bucketName name of bucket
879 // tagging tagging to be added
880 // error nil if success, otherwise error
881 func (client Client) SetBucketTagging(bucketName string, tagging Tagging, options ...Option) error {
884 bs, err = xml.Marshal(tagging)
890 buffer := new(bytes.Buffer)
893 contentType := http.DetectContentType(buffer.Bytes())
894 headers := map[string]string{}
895 headers[HTTPHeaderContentType] = contentType
897 params := map[string]interface{}{}
898 params["tagging"] = nil
899 resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
903 defer resp.Body.Close()
904 return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
907 // GetBucketTagging get tagging of the bucket
908 // bucketName name of bucket
909 // error nil if success, otherwise error
910 func (client Client) GetBucketTagging(bucketName string, options ...Option) (GetBucketTaggingResult, error) {
911 var out GetBucketTaggingResult
912 params := map[string]interface{}{}
913 params["tagging"] = nil
914 resp, err := client.do("GET", bucketName, params, nil, nil, options...)
918 defer resp.Body.Close()
920 err = xmlUnmarshal(resp.Body, &out)
925 // DeleteBucketTagging delete bucket tagging
926 // bucketName name of bucket
927 // error nil if success, otherwise error
929 func (client Client) DeleteBucketTagging(bucketName string, options ...Option) error {
930 params := map[string]interface{}{}
931 params["tagging"] = nil
932 resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
936 defer resp.Body.Close()
937 return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
940 // GetBucketStat get bucket stat
941 // bucketName the bucket name.
942 // error it's nil if no error, otherwise it's an error object.
943 func (client Client) GetBucketStat(bucketName string) (GetBucketStatResult, error) {
944 var out GetBucketStatResult
945 params := map[string]interface{}{}
947 resp, err := client.do("GET", bucketName, params, nil, nil)
951 defer resp.Body.Close()
953 err = xmlUnmarshal(resp.Body, &out)
957 // GetBucketPolicy API operation for Object Storage Service.
959 // Get the policy from the bucket.
961 // bucketName the bucket name.
963 // string return the bucket's policy, and it's only valid when error is nil.
965 // error it's nil if no error, otherwise it's an error object.
967 func (client Client) GetBucketPolicy(bucketName string, options ...Option) (string, error) {
968 params := map[string]interface{}{}
969 params["policy"] = nil
971 resp, err := client.do("GET", bucketName, params, nil, nil, options...)
975 defer resp.Body.Close()
977 body, err := ioutil.ReadAll(resp.Body)
983 // SetBucketPolicy API operation for Object Storage Service.
985 // Set the policy from the bucket.
987 // bucketName the bucket name.
989 // policy the bucket policy.
991 // error it's nil if no error, otherwise it's an error object.
993 func (client Client) SetBucketPolicy(bucketName string, policy string, options ...Option) error {
994 params := map[string]interface{}{}
995 params["policy"] = nil
997 buffer := strings.NewReader(policy)
999 resp, err := client.do("PUT", bucketName, params, nil, buffer, options...)
1003 defer resp.Body.Close()
1005 return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
1008 // DeleteBucketPolicy API operation for Object Storage Service.
1010 // Deletes the policy from the bucket.
1012 // bucketName the bucket name.
1014 // error it's nil if no error, otherwise it's an error object.
1016 func (client Client) DeleteBucketPolicy(bucketName string, options ...Option) error {
1017 params := map[string]interface{}{}
1018 params["policy"] = nil
1019 resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
1024 defer resp.Body.Close()
1025 return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
1028 // SetBucketRequestPayment API operation for Object Storage Service.
1030 // Set the requestPayment of bucket
1032 // bucketName the bucket name.
1034 // paymentConfig the payment configuration
1036 // error it's nil if no error, otherwise it's an error object.
1038 func (client Client) SetBucketRequestPayment(bucketName string, paymentConfig RequestPaymentConfiguration, options ...Option) error {
1039 params := map[string]interface{}{}
1040 params["requestPayment"] = nil
1043 bs, err := xml.Marshal(paymentConfig)
1049 buffer := new(bytes.Buffer)
1052 contentType := http.DetectContentType(buffer.Bytes())
1053 headers := map[string]string{}
1054 headers[HTTPHeaderContentType] = contentType
1056 resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
1060 defer resp.Body.Close()
1061 return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
1064 // GetBucketRequestPayment API operation for Object Storage Service.
1066 // Get bucket requestPayment
1068 // bucketName the bucket name.
1070 // RequestPaymentConfiguration the payment configuration
1072 // error it's nil if no error, otherwise it's an error object.
1074 func (client Client) GetBucketRequestPayment(bucketName string, options ...Option) (RequestPaymentConfiguration, error) {
1075 var out RequestPaymentConfiguration
1076 params := map[string]interface{}{}
1077 params["requestPayment"] = nil
1079 resp, err := client.do("GET", bucketName, params, nil, nil, options...)
1083 defer resp.Body.Close()
1085 err = xmlUnmarshal(resp.Body, &out)
1089 // GetUserQoSInfo API operation for Object Storage Service.
1093 // UserQoSConfiguration the User Qos and range Information.
1095 // error it's nil if no error, otherwise it's an error object.
1097 func (client Client) GetUserQoSInfo(options ...Option) (UserQoSConfiguration, error) {
1098 var out UserQoSConfiguration
1099 params := map[string]interface{}{}
1100 params["qosInfo"] = nil
1102 resp, err := client.do("GET", "", params, nil, nil, options...)
1106 defer resp.Body.Close()
1108 err = xmlUnmarshal(resp.Body, &out)
1112 // SetBucketQoSInfo API operation for Object Storage Service.
1114 // Set Bucket Qos information.
1116 // bucketName the bucket name.
1118 // qosConf the qos configuration.
1120 // error it's nil if no error, otherwise it's an error object.
1122 func (client Client) SetBucketQoSInfo(bucketName string, qosConf BucketQoSConfiguration, options ...Option) error {
1123 params := map[string]interface{}{}
1124 params["qosInfo"] = nil
1127 bs, err := xml.Marshal(qosConf)
1131 buffer := new(bytes.Buffer)
1134 contentTpye := http.DetectContentType(buffer.Bytes())
1135 headers := map[string]string{}
1136 headers[HTTPHeaderContentType] = contentTpye
1138 resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
1143 defer resp.Body.Close()
1144 return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
1147 // GetBucketQosInfo API operation for Object Storage Service.
1149 // Get Bucket Qos information.
1151 // bucketName the bucket name.
1153 // BucketQoSConfiguration the return qos configuration.
1155 // error it's nil if no error, otherwise it's an error object.
1157 func (client Client) GetBucketQosInfo(bucketName string, options ...Option) (BucketQoSConfiguration, error) {
1158 var out BucketQoSConfiguration
1159 params := map[string]interface{}{}
1160 params["qosInfo"] = nil
1162 resp, err := client.do("GET", bucketName, params, nil, nil, options...)
1166 defer resp.Body.Close()
1168 err = xmlUnmarshal(resp.Body, &out)
1172 // DeleteBucketQosInfo API operation for Object Storage Service.
1174 // Delete Bucket QoS information.
1176 // bucketName the bucket name.
1178 // error it's nil if no error, otherwise it's an error object.
1180 func (client Client) DeleteBucketQosInfo(bucketName string, options ...Option) error {
1181 params := map[string]interface{}{}
1182 params["qosInfo"] = nil
1184 resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
1188 defer resp.Body.Close()
1190 return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
1193 // SetBucketInventory API operation for Object Storage Service
1195 // Set the Bucket inventory.
1197 // bucketName tht bucket name.
1199 // inventoryConfig the inventory configuration.
1201 // error it's nil if no error, otherwise it's an error.
1203 func (client Client) SetBucketInventory(bucketName string, inventoryConfig InventoryConfiguration, options ...Option) error {
1204 params := map[string]interface{}{}
1205 params["inventoryId"] = inventoryConfig.Id
1206 params["inventory"] = nil
1209 bs, err := xml.Marshal(inventoryConfig)
1215 buffer := new(bytes.Buffer)
1218 contentType := http.DetectContentType(buffer.Bytes())
1219 headers := make(map[string]string)
1220 headers[HTTPHeaderContentType] = contentType
1222 resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
1228 defer resp.Body.Close()
1230 return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
1233 // GetBucketInventory API operation for Object Storage Service
1235 // Get the Bucket inventory.
1237 // bucketName tht bucket name.
1239 // strInventoryId the inventory id.
1241 // InventoryConfiguration the inventory configuration.
1243 // error it's nil if no error, otherwise it's an error.
1245 func (client Client) GetBucketInventory(bucketName string, strInventoryId string, options ...Option) (InventoryConfiguration, error) {
1246 var out InventoryConfiguration
1247 params := map[string]interface{}{}
1248 params["inventory"] = nil
1249 params["inventoryId"] = strInventoryId
1251 resp, err := client.do("GET", bucketName, params, nil, nil, options...)
1255 defer resp.Body.Close()
1257 err = xmlUnmarshal(resp.Body, &out)
1261 // ListBucketInventory API operation for Object Storage Service
1263 // List the Bucket inventory.
1265 // bucketName tht bucket name.
1267 // continuationToken the users token.
1269 // ListInventoryConfigurationsResult list all inventory configuration by .
1271 // error it's nil if no error, otherwise it's an error.
1273 func (client Client) ListBucketInventory(bucketName, continuationToken string, options ...Option) (ListInventoryConfigurationsResult, error) {
1274 var out ListInventoryConfigurationsResult
1275 params := map[string]interface{}{}
1276 params["inventory"] = nil
1277 if continuationToken == "" {
1278 params["continuation-token"] = nil
1280 params["continuation-token"] = continuationToken
1283 resp, err := client.do("GET", bucketName, params, nil, nil, options...)
1287 defer resp.Body.Close()
1289 err = xmlUnmarshal(resp.Body, &out)
1293 // DeleteBucketInventory API operation for Object Storage Service.
1295 // Delete Bucket inventory information.
1297 // bucketName tht bucket name.
1299 // strInventoryId the inventory id.
1301 // error it's nil if no error, otherwise it's an error.
1303 func (client Client) DeleteBucketInventory(bucketName, strInventoryId string, options ...Option) error {
1304 params := map[string]interface{}{}
1305 params["inventory"] = nil
1306 params["inventoryId"] = strInventoryId
1308 resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
1312 defer resp.Body.Close()
1314 return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
1317 // SetBucketAsyncTask API operation for set async fetch task
1319 // bucketName tht bucket name.
1321 // asynConf configruation
1323 // error it's nil if success, otherwise it's an error.
1324 func (client Client) SetBucketAsyncTask(bucketName string, asynConf AsyncFetchTaskConfiguration, options ...Option) (AsyncFetchTaskResult, error) {
1325 var out AsyncFetchTaskResult
1326 params := map[string]interface{}{}
1327 params["asyncFetch"] = nil
1330 bs, err := xml.Marshal(asynConf)
1336 buffer := new(bytes.Buffer)
1339 contentType := http.DetectContentType(buffer.Bytes())
1340 headers := make(map[string]string)
1341 headers[HTTPHeaderContentType] = contentType
1343 resp, err := client.do("POST", bucketName, params, headers, buffer, options...)
1349 defer resp.Body.Close()
1350 err = xmlUnmarshal(resp.Body, &out)
1354 // GetBucketAsyncTask API operation for set async fetch task
1356 // bucketName tht bucket name.
1358 // taskid returned by SetBucketAsyncTask
1360 // error it's nil if success, otherwise it's an error.
1361 func (client Client) GetBucketAsyncTask(bucketName string, taskID string, options ...Option) (AsynFetchTaskInfo, error) {
1362 var out AsynFetchTaskInfo
1363 params := map[string]interface{}{}
1364 params["asyncFetch"] = nil
1366 headers := make(map[string]string)
1367 headers[HTTPHeaderOssTaskID] = taskID
1368 resp, err := client.do("GET", bucketName, params, headers, nil, options...)
1372 defer resp.Body.Close()
1373 err = xmlUnmarshal(resp.Body, &out)
1377 // InitiateBucketWorm creates bucket worm Configuration
1378 // bucketName the bucket name.
1379 // retentionDays the retention period in days
1380 // error it's nil if no error, otherwise it's an error object.
1382 func (client Client) InitiateBucketWorm(bucketName string, retentionDays int, options ...Option) (string, error) {
1383 var initiateWormConf InitiateWormConfiguration
1384 initiateWormConf.RetentionPeriodInDays = retentionDays
1386 var respHeader http.Header
1387 isOptSet, _, _ := IsOptionSet(options, responseHeader)
1389 options = append(options, GetResponseHeader(&respHeader))
1392 bs, err := xml.Marshal(initiateWormConf)
1396 buffer := new(bytes.Buffer)
1399 contentType := http.DetectContentType(buffer.Bytes())
1400 headers := make(map[string]string)
1401 headers[HTTPHeaderContentType] = contentType
1403 params := map[string]interface{}{}
1404 params["worm"] = nil
1406 resp, err := client.do("POST", bucketName, params, headers, buffer, options...)
1410 defer resp.Body.Close()
1412 respOpt, _ := FindOption(options, responseHeader, nil)
1414 err = CheckRespCode(resp.StatusCode, []int{http.StatusOK})
1415 if err == nil && respOpt != nil {
1416 wormID = (respOpt.(*http.Header)).Get("x-oss-worm-id")
1421 // AbortBucketWorm delete bucket worm Configuration
1422 // bucketName the bucket name.
1423 // error it's nil if no error, otherwise it's an error object.
1425 func (client Client) AbortBucketWorm(bucketName string, options ...Option) error {
1426 params := map[string]interface{}{}
1427 params["worm"] = nil
1428 resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
1432 defer resp.Body.Close()
1433 return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
1436 // CompleteBucketWorm complete bucket worm Configuration
1437 // bucketName the bucket name.
1438 // wormID the worm id
1439 // error it's nil if no error, otherwise it's an error object.
1441 func (client Client) CompleteBucketWorm(bucketName string, wormID string, options ...Option) error {
1442 params := map[string]interface{}{}
1443 params["wormId"] = wormID
1444 resp, err := client.do("POST", bucketName, params, nil, nil, options...)
1448 defer resp.Body.Close()
1449 return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
1452 // ExtendBucketWorm exetend bucket worm Configuration
1453 // bucketName the bucket name.
1454 // retentionDays the retention period in days
1455 // wormID the worm id
1456 // error it's nil if no error, otherwise it's an error object.
1458 func (client Client) ExtendBucketWorm(bucketName string, retentionDays int, wormID string, options ...Option) error {
1459 var extendWormConf ExtendWormConfiguration
1460 extendWormConf.RetentionPeriodInDays = retentionDays
1462 bs, err := xml.Marshal(extendWormConf)
1466 buffer := new(bytes.Buffer)
1469 contentType := http.DetectContentType(buffer.Bytes())
1470 headers := make(map[string]string)
1471 headers[HTTPHeaderContentType] = contentType
1473 params := map[string]interface{}{}
1474 params["wormId"] = wormID
1475 params["wormExtend"] = nil
1477 resp, err := client.do("POST", bucketName, params, headers, buffer, options...)
1481 defer resp.Body.Close()
1482 return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
1485 // GetBucketWorm get bucket worm Configuration
1486 // bucketName the bucket name.
1487 // error it's nil if no error, otherwise it's an error object.
1489 func (client Client) GetBucketWorm(bucketName string, options ...Option) (WormConfiguration, error) {
1490 var out WormConfiguration
1491 params := map[string]interface{}{}
1492 params["worm"] = nil
1494 resp, err := client.do("GET", bucketName, params, nil, nil, options...)
1498 defer resp.Body.Close()
1499 err = xmlUnmarshal(resp.Body, &out)
1503 // LimitUploadSpeed set upload bandwidth limit speed,default is 0,unlimited
1504 // upSpeed KB/s, 0 is unlimited,default is 0
1505 // error it's nil if success, otherwise failure
1506 func (client Client) LimitUploadSpeed(upSpeed int) error {
1507 if client.Config == nil {
1508 return fmt.Errorf("client config is nil")
1510 return client.Config.LimitUploadSpeed(upSpeed)
1513 // UseCname sets the flag of using CName. By default it's false.
1515 // isUseCname true: the endpoint has the CName, false: the endpoint does not have cname. Default is false.
1517 func UseCname(isUseCname bool) ClientOption {
1518 return func(client *Client) {
1519 client.Config.IsCname = isUseCname
1520 client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
1524 // Timeout sets the HTTP timeout in seconds.
1526 // connectTimeoutSec HTTP timeout in seconds. Default is 10 seconds. 0 means infinite (not recommended)
1527 // readWriteTimeout HTTP read or write's timeout in seconds. Default is 20 seconds. 0 means infinite.
1529 func Timeout(connectTimeoutSec, readWriteTimeout int64) ClientOption {
1530 return func(client *Client) {
1531 client.Config.HTTPTimeout.ConnectTimeout =
1532 time.Second * time.Duration(connectTimeoutSec)
1533 client.Config.HTTPTimeout.ReadWriteTimeout =
1534 time.Second * time.Duration(readWriteTimeout)
1535 client.Config.HTTPTimeout.HeaderTimeout =
1536 time.Second * time.Duration(readWriteTimeout)
1537 client.Config.HTTPTimeout.IdleConnTimeout =
1538 time.Second * time.Duration(readWriteTimeout)
1539 client.Config.HTTPTimeout.LongTimeout =
1540 time.Second * time.Duration(readWriteTimeout*10)
1544 // SecurityToken sets the temporary user's SecurityToken.
1548 func SecurityToken(token string) ClientOption {
1549 return func(client *Client) {
1550 client.Config.SecurityToken = strings.TrimSpace(token)
1554 // EnableMD5 enables MD5 validation.
1556 // isEnableMD5 true: enable MD5 validation; false: disable MD5 validation.
1558 func EnableMD5(isEnableMD5 bool) ClientOption {
1559 return func(client *Client) {
1560 client.Config.IsEnableMD5 = isEnableMD5
1564 // MD5ThresholdCalcInMemory sets the memory usage threshold for computing the MD5, default is 16MB.
1566 // threshold the memory threshold in bytes. When the uploaded content is more than 16MB, the temp file is used for computing the MD5.
1568 func MD5ThresholdCalcInMemory(threshold int64) ClientOption {
1569 return func(client *Client) {
1570 client.Config.MD5Threshold = threshold
1574 // EnableCRC enables the CRC checksum. Default is true.
1576 // isEnableCRC true: enable CRC checksum; false: disable the CRC checksum.
1578 func EnableCRC(isEnableCRC bool) ClientOption {
1579 return func(client *Client) {
1580 client.Config.IsEnableCRC = isEnableCRC
1584 // UserAgent specifies UserAgent. The default is aliyun-sdk-go/1.2.0 (windows/-/amd64;go1.5.2).
1586 // userAgent the user agent string.
1588 func UserAgent(userAgent string) ClientOption {
1589 return func(client *Client) {
1590 client.Config.UserAgent = userAgent
1591 client.Config.UserSetUa = true
1595 // Proxy sets the proxy (optional). The default is not using proxy.
1597 // proxyHost the proxy host in the format "host:port". For example, proxy.com:80 .
1599 func Proxy(proxyHost string) ClientOption {
1600 return func(client *Client) {
1601 client.Config.IsUseProxy = true
1602 client.Config.ProxyHost = proxyHost
1603 client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
1607 // AuthProxy sets the proxy information with user name and password.
1609 // proxyHost the proxy host in the format "host:port". For example, proxy.com:80 .
1610 // proxyUser the proxy user name.
1611 // proxyPassword the proxy password.
1613 func AuthProxy(proxyHost, proxyUser, proxyPassword string) ClientOption {
1614 return func(client *Client) {
1615 client.Config.IsUseProxy = true
1616 client.Config.ProxyHost = proxyHost
1617 client.Config.IsAuthProxy = true
1618 client.Config.ProxyUser = proxyUser
1619 client.Config.ProxyPassword = proxyPassword
1620 client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
1625 // HTTPClient sets the http.Client in use to the one passed in
1627 func HTTPClient(HTTPClient *http.Client) ClientOption {
1628 return func(client *Client) {
1629 client.HTTPClient = HTTPClient
1634 // SetLogLevel sets the oss sdk log level
1636 func SetLogLevel(LogLevel int) ClientOption {
1637 return func(client *Client) {
1638 client.Config.LogLevel = LogLevel
1643 // SetLogger sets the oss sdk logger
1645 func SetLogger(Logger *log.Logger) ClientOption {
1646 return func(client *Client) {
1647 client.Config.Logger = Logger
1651 // SetCredentialsProvider sets funciton for get the user's ak
1652 func SetCredentialsProvider(provider CredentialsProvider) ClientOption {
1653 return func(client *Client) {
1654 client.Config.CredentialsProvider = provider
1658 // SetLocalAddr sets funciton for local addr
1659 func SetLocalAddr(localAddr net.Addr) ClientOption {
1660 return func(client *Client) {
1661 client.Config.LocalAddr = localAddr
1665 // AuthVersion sets auth version: v1 or v2 signature which oss_server needed
1666 func AuthVersion(authVersion AuthVersionType) ClientOption {
1667 return func(client *Client) {
1668 client.Config.AuthVersion = authVersion
1672 // AdditionalHeaders sets special http headers needed to be signed
1673 func AdditionalHeaders(headers []string) ClientOption {
1674 return func(client *Client) {
1675 client.Config.AdditionalHeaders = headers
1679 // only effective from go1.7 onward,RedirectEnabled set http redirect enabled or not
1680 func RedirectEnabled(enabled bool) ClientOption {
1681 return func(client *Client) {
1682 client.Config.RedirectEnabled = enabled
1687 func (client Client) do(method, bucketName string, params map[string]interface{},
1688 headers map[string]string, data io.Reader, options ...Option) (*Response, error) {
1689 err := CheckBucketName(bucketName)
1690 if len(bucketName) > 0 && err != nil {
1695 addHeaders := make(map[string]string)
1696 err = handleOptions(addHeaders, options)
1703 headers = make(map[string]string)
1706 for k, v := range addHeaders {
1707 if _, ok := headers[k]; !ok {
1712 resp, err := client.Conn.Do(method, bucketName, "", params, headers, data, 0, nil)
1714 // get response header
1715 respHeader, _ := FindOption(options, responseHeader, nil)
1716 if respHeader != nil {
1717 pRespHeader := respHeader.(*http.Header)
1718 *pRespHeader = resp.Headers