1 Star 0 Fork 0

Cinus / aliyun-oss-go-sdk

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
client.go 59.10 KB
一键复制 编辑 原始数据 按行查看 历史
taowei.wtw 提交于 2021-11-10 19:07 . add CreateBucketXml
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011
// Package oss implements functions for access oss service.
// It has two main struct Client and Bucket.
package oss
import (
"bytes"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"strings"
"time"
)
// 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).
// Object related operations are done by Bucket class.
// Users use oss.New to create Client instance.
//
type (
// Client OSS client
Client struct {
Config *Config // OSS client configuration
Conn *Conn // Send HTTP request
HTTPClient *http.Client //http.Client to use - if nil will make its own
}
// ClientOption client option such as UseCname, Timeout, SecurityToken.
ClientOption func(*Client)
)
// New creates a new client.
//
// endpoint the OSS datacenter endpoint such as http://oss-cn-hangzhou.aliyuncs.com .
// accessKeyId access key Id.
// accessKeySecret access key secret.
//
// Client creates the new client instance, the returned value is valid when error is nil.
// error it's nil if no error, otherwise it's an error object.
//
func New(endpoint, accessKeyID, accessKeySecret string, options ...ClientOption) (*Client, error) {
// Configuration
config := getDefaultOssConfig()
config.Endpoint = endpoint
config.AccessKeyID = accessKeyID
config.AccessKeySecret = accessKeySecret
// URL parse
url := &urlMaker{}
err := url.Init(config.Endpoint, config.IsCname, config.IsUseProxy)
if err != nil {
return nil, err
}
// HTTP connect
conn := &Conn{config: config, url: url}
// OSS client
client := &Client{
Config: config,
Conn: conn,
}
// Client options parse
for _, option := range options {
option(client)
}
if config.AuthVersion != AuthV1 && config.AuthVersion != AuthV2 {
return nil, fmt.Errorf("Init client Error, invalid Auth version: %v", config.AuthVersion)
}
// Create HTTP connection
err = conn.init(config, url, client.HTTPClient)
return client, err
}
// Bucket gets the bucket instance.
//
// bucketName the bucket name.
// Bucket the bucket object, when error is nil.
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) Bucket(bucketName string) (*Bucket, error) {
err := CheckBucketName(bucketName)
if err != nil {
return nil, err
}
return &Bucket{
client,
bucketName,
}, nil
}
// CreateBucket creates a bucket.
//
// bucketName the bucket name, it's globably unique and immutable. The bucket name can only consist of lowercase letters, numbers and dash ('-').
// It must start with lowercase letter or number and the length can only be between 3 and 255.
// options options for creating the bucket, with optional ACL. The ACL could be ACLPrivate, ACLPublicRead, and ACLPublicReadWrite. By default it's ACLPrivate.
// It could also be specified with StorageClass option, which supports StorageStandard, StorageIA(infrequent access), StorageArchive.
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) CreateBucket(bucketName string, options ...Option) error {
headers := make(map[string]string)
handleOptions(headers, options)
buffer := new(bytes.Buffer)
var cbConfig createBucketConfiguration
cbConfig.StorageClass = StorageStandard
isStorageSet, valStroage, _ := IsOptionSet(options, storageClass)
isRedundancySet, valRedundancy, _ := IsOptionSet(options, redundancyType)
isObjectHashFuncSet, valHashFunc, _ := IsOptionSet(options, objectHashFunc)
if isStorageSet {
cbConfig.StorageClass = valStroage.(StorageClassType)
}
if isRedundancySet {
cbConfig.DataRedundancyType = valRedundancy.(DataRedundancyType)
}
if isObjectHashFuncSet {
cbConfig.ObjectHashFunction = valHashFunc.(ObjecthashFuncType)
}
bs, err := xml.Marshal(cbConfig)
if err != nil {
return err
}
buffer.Write(bs)
contentType := http.DetectContentType(buffer.Bytes())
headers[HTTPHeaderContentType] = contentType
params := map[string]interface{}{}
resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
}
// create bucket xml
func (client Client) CreateBucketXml(bucketName string, xmlBody string, options ...Option) error {
buffer := new(bytes.Buffer)
buffer.Write([]byte(xmlBody))
contentType := http.DetectContentType(buffer.Bytes())
headers := map[string]string{}
headers[HTTPHeaderContentType] = contentType
params := map[string]interface{}{}
resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
}
// ListBuckets lists buckets of the current account under the given endpoint, with optional filters.
//
// options specifies the filters such as Prefix, Marker and MaxKeys. Prefix is the bucket name's prefix filter.
// And marker makes sure the returned buckets' name are greater than it in lexicographic order.
// Maxkeys limits the max keys to return, and by default it's 100 and up to 1000.
// For the common usage scenario, please check out list_bucket.go in the sample.
// ListBucketsResponse the response object if error is nil.
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) ListBuckets(options ...Option) (ListBucketsResult, error) {
var out ListBucketsResult
params, err := GetRawParams(options)
if err != nil {
return out, err
}
resp, err := client.do("GET", "", params, nil, nil, options...)
if err != nil {
return out, err
}
defer resp.Body.Close()
err = xmlUnmarshal(resp.Body, &out)
return out, err
}
// IsBucketExist checks if the bucket exists
//
// bucketName the bucket name.
//
// bool true if it exists, and it's only valid when error is nil.
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) IsBucketExist(bucketName string) (bool, error) {
listRes, err := client.ListBuckets(Prefix(bucketName), MaxKeys(1))
if err != nil {
return false, err
}
if len(listRes.Buckets) == 1 && listRes.Buckets[0].Name == bucketName {
return true, nil
}
return false, nil
}
// DeleteBucket deletes the bucket. Only empty bucket can be deleted (no object and parts).
//
// bucketName the bucket name.
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) DeleteBucket(bucketName string, options ...Option) error {
params := map[string]interface{}{}
resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
}
// GetBucketLocation gets the bucket location.
//
// Checks out the following link for more information :
// https://help.aliyun.com/document_detail/oss/user_guide/oss_concept/endpoint.html
//
// bucketName the bucket name
//
// string bucket's datacenter location
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) GetBucketLocation(bucketName string, options ...Option) (string, error) {
params := map[string]interface{}{}
params["location"] = nil
resp, err := client.do("GET", bucketName, params, nil, nil, options...)
if err != nil {
return "", err
}
defer resp.Body.Close()
var LocationConstraint string
err = xmlUnmarshal(resp.Body, &LocationConstraint)
return LocationConstraint, err
}
// SetBucketACL sets bucket's ACL.
//
// bucketName the bucket name
// bucketAcl the bucket ACL: ACLPrivate, ACLPublicRead and ACLPublicReadWrite.
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) SetBucketACL(bucketName string, bucketACL ACLType, options ...Option) error {
headers := map[string]string{HTTPHeaderOssACL: string(bucketACL)}
params := map[string]interface{}{}
params["acl"] = nil
resp, err := client.do("PUT", bucketName, params, headers, nil, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
}
// GetBucketACL gets the bucket ACL.
//
// bucketName the bucket name.
//
// GetBucketAclResponse the result object, and it's only valid when error is nil.
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) GetBucketACL(bucketName string, options ...Option) (GetBucketACLResult, error) {
var out GetBucketACLResult
params := map[string]interface{}{}
params["acl"] = nil
resp, err := client.do("GET", bucketName, params, nil, nil, options...)
if err != nil {
return out, err
}
defer resp.Body.Close()
err = xmlUnmarshal(resp.Body, &out)
return out, err
}
// SetBucketLifecycle sets the bucket's lifecycle.
//
// For more information, checks out following link:
// https://help.aliyun.com/document_detail/oss/user_guide/manage_object/object_lifecycle.html
//
// bucketName the bucket name.
// rules the lifecycle rules. There're two kind of rules: absolute time expiration and relative time expiration in days and day/month/year respectively.
// Check out sample/bucket_lifecycle.go for more details.
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) SetBucketLifecycle(bucketName string, rules []LifecycleRule, options ...Option) error {
err := verifyLifecycleRules(rules)
if err != nil {
return err
}
lifecycleCfg := LifecycleConfiguration{Rules: rules}
bs, err := xml.Marshal(lifecycleCfg)
if err != nil {
return err
}
buffer := new(bytes.Buffer)
buffer.Write(bs)
contentType := http.DetectContentType(buffer.Bytes())
headers := map[string]string{}
headers[HTTPHeaderContentType] = contentType
params := map[string]interface{}{}
params["lifecycle"] = nil
resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
}
// SetBucketLifecycleXml sets the bucket's lifecycle rule from xml config
func (client Client) SetBucketLifecycleXml(bucketName string, xmlBody string, options ...Option) error {
buffer := new(bytes.Buffer)
buffer.Write([]byte(xmlBody))
contentType := http.DetectContentType(buffer.Bytes())
headers := map[string]string{}
headers[HTTPHeaderContentType] = contentType
params := map[string]interface{}{}
params["lifecycle"] = nil
resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
}
// DeleteBucketLifecycle deletes the bucket's lifecycle.
//
//
// bucketName the bucket name.
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) DeleteBucketLifecycle(bucketName string, options ...Option) error {
params := map[string]interface{}{}
params["lifecycle"] = nil
resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
}
// GetBucketLifecycle gets the bucket's lifecycle settings.
//
// bucketName the bucket name.
//
// GetBucketLifecycleResponse the result object upon successful request. It's only valid when error is nil.
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) GetBucketLifecycle(bucketName string, options ...Option) (GetBucketLifecycleResult, error) {
var out GetBucketLifecycleResult
params := map[string]interface{}{}
params["lifecycle"] = nil
resp, err := client.do("GET", bucketName, params, nil, nil, options...)
if err != nil {
return out, err
}
defer resp.Body.Close()
err = xmlUnmarshal(resp.Body, &out)
// NonVersionTransition is not suggested to use
// to keep compatible
for k, rule := range out.Rules {
if len(rule.NonVersionTransitions) > 0 {
out.Rules[k].NonVersionTransition = &(out.Rules[k].NonVersionTransitions[0])
}
}
return out, err
}
// SetBucketReferer sets the bucket's referer whitelist and the flag if allowing empty referrer.
//
// 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
// the allowing empty referrer flag. Note that this applies to requests from webbrowser only.
// For example, for a bucket os-example and its referrer http://www.aliyun.com, all requests from this URL could access the bucket.
// For more information, please check out this link :
// https://help.aliyun.com/document_detail/oss/user_guide/security_management/referer.html
//
// bucketName the bucket name.
// referers the referrer white list. A bucket could have a referrer list and each referrer supports one '*' and multiple '?' as wildcards.
// The sample could be found in sample/bucket_referer.go
// allowEmptyReferer the flag of allowing empty referrer. By default it's true.
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) SetBucketReferer(bucketName string, referers []string, allowEmptyReferer bool, options ...Option) error {
rxml := RefererXML{}
rxml.AllowEmptyReferer = allowEmptyReferer
if referers == nil {
rxml.RefererList = append(rxml.RefererList, "")
} else {
for _, referer := range referers {
rxml.RefererList = append(rxml.RefererList, referer)
}
}
bs, err := xml.Marshal(rxml)
if err != nil {
return err
}
buffer := new(bytes.Buffer)
buffer.Write(bs)
contentType := http.DetectContentType(buffer.Bytes())
headers := map[string]string{}
headers[HTTPHeaderContentType] = contentType
params := map[string]interface{}{}
params["referer"] = nil
resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
}
// GetBucketReferer gets the bucket's referrer white list.
//
// bucketName the bucket name.
//
// GetBucketRefererResponse the result object upon successful request. It's only valid when error is nil.
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) GetBucketReferer(bucketName string, options ...Option) (GetBucketRefererResult, error) {
var out GetBucketRefererResult
params := map[string]interface{}{}
params["referer"] = nil
resp, err := client.do("GET", bucketName, params, nil, nil, options...)
if err != nil {
return out, err
}
defer resp.Body.Close()
err = xmlUnmarshal(resp.Body, &out)
return out, err
}
// SetBucketLogging sets the bucket logging settings.
//
// OSS could automatically store the access log. Only the bucket owner could enable the logging.
// Once enabled, OSS would save all the access log into hourly log files in a specified bucket.
// For more information, please check out https://help.aliyun.com/document_detail/oss/user_guide/security_management/logging.html
//
// bucketName bucket name to enable the log.
// targetBucket the target bucket name to store the log files.
// targetPrefix the log files' prefix.
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) SetBucketLogging(bucketName, targetBucket, targetPrefix string,
isEnable bool, options ...Option) error {
var err error
var bs []byte
if isEnable {
lxml := LoggingXML{}
lxml.LoggingEnabled.TargetBucket = targetBucket
lxml.LoggingEnabled.TargetPrefix = targetPrefix
bs, err = xml.Marshal(lxml)
} else {
lxml := loggingXMLEmpty{}
bs, err = xml.Marshal(lxml)
}
if err != nil {
return err
}
buffer := new(bytes.Buffer)
buffer.Write(bs)
contentType := http.DetectContentType(buffer.Bytes())
headers := map[string]string{}
headers[HTTPHeaderContentType] = contentType
params := map[string]interface{}{}
params["logging"] = nil
resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
}
// DeleteBucketLogging deletes the logging configuration to disable the logging on the bucket.
//
// bucketName the bucket name to disable the logging.
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) DeleteBucketLogging(bucketName string, options ...Option) error {
params := map[string]interface{}{}
params["logging"] = nil
resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
}
// GetBucketLogging gets the bucket's logging settings
//
// bucketName the bucket name
// GetBucketLoggingResponse the result object upon successful request. It's only valid when error is nil.
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) GetBucketLogging(bucketName string, options ...Option) (GetBucketLoggingResult, error) {
var out GetBucketLoggingResult
params := map[string]interface{}{}
params["logging"] = nil
resp, err := client.do("GET", bucketName, params, nil, nil, options...)
if err != nil {
return out, err
}
defer resp.Body.Close()
err = xmlUnmarshal(resp.Body, &out)
return out, err
}
// SetBucketWebsite sets the bucket's static website's index and error page.
//
// 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.
// For more information, please check out: https://help.aliyun.com/document_detail/oss/user_guide/static_host_website.html
//
// bucketName the bucket name to enable static web site.
// indexDocument index page.
// errorDocument error page.
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) SetBucketWebsite(bucketName, indexDocument, errorDocument string, options ...Option) error {
wxml := WebsiteXML{}
wxml.IndexDocument.Suffix = indexDocument
wxml.ErrorDocument.Key = errorDocument
bs, err := xml.Marshal(wxml)
if err != nil {
return err
}
buffer := new(bytes.Buffer)
buffer.Write(bs)
contentType := http.DetectContentType(buffer.Bytes())
headers := make(map[string]string)
headers[HTTPHeaderContentType] = contentType
params := map[string]interface{}{}
params["website"] = nil
resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
}
// SetBucketWebsiteDetail sets the bucket's static website's detail
//
// 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.
// For more information, please check out: https://help.aliyun.com/document_detail/oss/user_guide/static_host_website.html
//
// bucketName the bucket name to enable static web site.
//
// wxml the website's detail
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) SetBucketWebsiteDetail(bucketName string, wxml WebsiteXML, options ...Option) error {
bs, err := xml.Marshal(wxml)
if err != nil {
return err
}
buffer := new(bytes.Buffer)
buffer.Write(bs)
contentType := http.DetectContentType(buffer.Bytes())
headers := make(map[string]string)
headers[HTTPHeaderContentType] = contentType
params := map[string]interface{}{}
params["website"] = nil
resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
}
// SetBucketWebsiteXml sets the bucket's static website's rule
//
// 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.
// For more information, please check out: https://help.aliyun.com/document_detail/oss/user_guide/static_host_website.html
//
// bucketName the bucket name to enable static web site.
//
// wxml the website's detail
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) SetBucketWebsiteXml(bucketName string, webXml string, options ...Option) error {
buffer := new(bytes.Buffer)
buffer.Write([]byte(webXml))
contentType := http.DetectContentType(buffer.Bytes())
headers := make(map[string]string)
headers[HTTPHeaderContentType] = contentType
params := map[string]interface{}{}
params["website"] = nil
resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
}
// DeleteBucketWebsite deletes the bucket's static web site settings.
//
// bucketName the bucket name.
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) DeleteBucketWebsite(bucketName string, options ...Option) error {
params := map[string]interface{}{}
params["website"] = nil
resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
}
// GetBucketWebsite gets the bucket's default page (index page) and the error page.
//
// bucketName the bucket name
//
// GetBucketWebsiteResponse the result object upon successful request. It's only valid when error is nil.
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) GetBucketWebsite(bucketName string, options ...Option) (GetBucketWebsiteResult, error) {
var out GetBucketWebsiteResult
params := map[string]interface{}{}
params["website"] = nil
resp, err := client.do("GET", bucketName, params, nil, nil, options...)
if err != nil {
return out, err
}
defer resp.Body.Close()
err = xmlUnmarshal(resp.Body, &out)
return out, err
}
// GetBucketWebsiteXml gets the bucket's website config xml config.
//
// bucketName the bucket name
//
// string the bucket's xml config, It's only valid when error is nil.
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) GetBucketWebsiteXml(bucketName string, options ...Option) (string, error) {
params := map[string]interface{}{}
params["website"] = nil
resp, err := client.do("GET", bucketName, params, nil, nil, options...)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
out := string(body)
return out, err
}
// SetBucketCORS sets the bucket's CORS rules
//
// For more information, please check out https://help.aliyun.com/document_detail/oss/user_guide/security_management/cors.html
//
// bucketName the bucket name
// corsRules the CORS rules to set. The related sample code is in sample/bucket_cors.go.
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) SetBucketCORS(bucketName string, corsRules []CORSRule, options ...Option) error {
corsxml := CORSXML{}
for _, v := range corsRules {
cr := CORSRule{}
cr.AllowedMethod = v.AllowedMethod
cr.AllowedOrigin = v.AllowedOrigin
cr.AllowedHeader = v.AllowedHeader
cr.ExposeHeader = v.ExposeHeader
cr.MaxAgeSeconds = v.MaxAgeSeconds
corsxml.CORSRules = append(corsxml.CORSRules, cr)
}
bs, err := xml.Marshal(corsxml)
if err != nil {
return err
}
buffer := new(bytes.Buffer)
buffer.Write(bs)
contentType := http.DetectContentType(buffer.Bytes())
headers := map[string]string{}
headers[HTTPHeaderContentType] = contentType
params := map[string]interface{}{}
params["cors"] = nil
resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
}
// DeleteBucketCORS deletes the bucket's static website settings.
//
// bucketName the bucket name.
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) DeleteBucketCORS(bucketName string, options ...Option) error {
params := map[string]interface{}{}
params["cors"] = nil
resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
}
// GetBucketCORS gets the bucket's CORS settings.
//
// bucketName the bucket name.
// GetBucketCORSResult the result object upon successful request. It's only valid when error is nil.
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) GetBucketCORS(bucketName string, options ...Option) (GetBucketCORSResult, error) {
var out GetBucketCORSResult
params := map[string]interface{}{}
params["cors"] = nil
resp, err := client.do("GET", bucketName, params, nil, nil, options...)
if err != nil {
return out, err
}
defer resp.Body.Close()
err = xmlUnmarshal(resp.Body, &out)
return out, err
}
// GetBucketInfo gets the bucket information.
//
// bucketName the bucket name.
// GetBucketInfoResult the result object upon successful request. It's only valid when error is nil.
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) GetBucketInfo(bucketName string, options ...Option) (GetBucketInfoResult, error) {
var out GetBucketInfoResult
params := map[string]interface{}{}
params["bucketInfo"] = nil
resp, err := client.do("GET", bucketName, params, nil, nil, options...)
if err != nil {
return out, err
}
defer resp.Body.Close()
err = xmlUnmarshal(resp.Body, &out)
// convert None to ""
if err == nil {
if out.BucketInfo.SseRule.KMSMasterKeyID == "None" {
out.BucketInfo.SseRule.KMSMasterKeyID = ""
}
if out.BucketInfo.SseRule.SSEAlgorithm == "None" {
out.BucketInfo.SseRule.SSEAlgorithm = ""
}
if out.BucketInfo.SseRule.KMSDataEncryption == "None" {
out.BucketInfo.SseRule.KMSDataEncryption = ""
}
}
return out, err
}
// SetBucketVersioning set bucket versioning:Enabled、Suspended
// bucketName the bucket name.
// error it's nil if no error, otherwise it's an error object.
func (client Client) SetBucketVersioning(bucketName string, versioningConfig VersioningConfig, options ...Option) error {
var err error
var bs []byte
bs, err = xml.Marshal(versioningConfig)
if err != nil {
return err
}
buffer := new(bytes.Buffer)
buffer.Write(bs)
contentType := http.DetectContentType(buffer.Bytes())
headers := map[string]string{}
headers[HTTPHeaderContentType] = contentType
params := map[string]interface{}{}
params["versioning"] = nil
resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
}
// GetBucketVersioning get bucket versioning status:Enabled、Suspended
// bucketName the bucket name.
// error it's nil if no error, otherwise it's an error object.
func (client Client) GetBucketVersioning(bucketName string, options ...Option) (GetBucketVersioningResult, error) {
var out GetBucketVersioningResult
params := map[string]interface{}{}
params["versioning"] = nil
resp, err := client.do("GET", bucketName, params, nil, nil, options...)
if err != nil {
return out, err
}
defer resp.Body.Close()
err = xmlUnmarshal(resp.Body, &out)
return out, err
}
// SetBucketEncryption set bucket encryption config
// bucketName the bucket name.
// error it's nil if no error, otherwise it's an error object.
func (client Client) SetBucketEncryption(bucketName string, encryptionRule ServerEncryptionRule, options ...Option) error {
var err error
var bs []byte
bs, err = xml.Marshal(encryptionRule)
if err != nil {
return err
}
buffer := new(bytes.Buffer)
buffer.Write(bs)
contentType := http.DetectContentType(buffer.Bytes())
headers := map[string]string{}
headers[HTTPHeaderContentType] = contentType
params := map[string]interface{}{}
params["encryption"] = nil
resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
}
// GetBucketEncryption get bucket encryption
// bucketName the bucket name.
// error it's nil if no error, otherwise it's an error object.
func (client Client) GetBucketEncryption(bucketName string, options ...Option) (GetBucketEncryptionResult, error) {
var out GetBucketEncryptionResult
params := map[string]interface{}{}
params["encryption"] = nil
resp, err := client.do("GET", bucketName, params, nil, nil, options...)
if err != nil {
return out, err
}
defer resp.Body.Close()
err = xmlUnmarshal(resp.Body, &out)
return out, err
}
// DeleteBucketEncryption delete bucket encryption config
// bucketName the bucket name.
// error it's nil if no error, otherwise it's an error bucket
func (client Client) DeleteBucketEncryption(bucketName string, options ...Option) error {
params := map[string]interface{}{}
params["encryption"] = nil
resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
}
//
// SetBucketTagging add tagging to bucket
// bucketName name of bucket
// tagging tagging to be added
// error nil if success, otherwise error
func (client Client) SetBucketTagging(bucketName string, tagging Tagging, options ...Option) error {
var err error
var bs []byte
bs, err = xml.Marshal(tagging)
if err != nil {
return err
}
buffer := new(bytes.Buffer)
buffer.Write(bs)
contentType := http.DetectContentType(buffer.Bytes())
headers := map[string]string{}
headers[HTTPHeaderContentType] = contentType
params := map[string]interface{}{}
params["tagging"] = nil
resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
}
// GetBucketTagging get tagging of the bucket
// bucketName name of bucket
// error nil if success, otherwise error
func (client Client) GetBucketTagging(bucketName string, options ...Option) (GetBucketTaggingResult, error) {
var out GetBucketTaggingResult
params := map[string]interface{}{}
params["tagging"] = nil
resp, err := client.do("GET", bucketName, params, nil, nil, options...)
if err != nil {
return out, err
}
defer resp.Body.Close()
err = xmlUnmarshal(resp.Body, &out)
return out, err
}
//
// DeleteBucketTagging delete bucket tagging
// bucketName name of bucket
// error nil if success, otherwise error
//
func (client Client) DeleteBucketTagging(bucketName string, options ...Option) error {
params := map[string]interface{}{}
params["tagging"] = nil
resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
}
// GetBucketStat get bucket stat
// bucketName the bucket name.
// error it's nil if no error, otherwise it's an error object.
func (client Client) GetBucketStat(bucketName string, options ...Option) (GetBucketStatResult, error) {
var out GetBucketStatResult
params := map[string]interface{}{}
params["stat"] = nil
resp, err := client.do("GET", bucketName, params, nil, nil, options...)
if err != nil {
return out, err
}
defer resp.Body.Close()
err = xmlUnmarshal(resp.Body, &out)
return out, err
}
// GetBucketPolicy API operation for Object Storage Service.
//
// Get the policy from the bucket.
//
// bucketName the bucket name.
//
// string return the bucket's policy, and it's only valid when error is nil.
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) GetBucketPolicy(bucketName string, options ...Option) (string, error) {
params := map[string]interface{}{}
params["policy"] = nil
resp, err := client.do("GET", bucketName, params, nil, nil, options...)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
out := string(body)
return out, err
}
// SetBucketPolicy API operation for Object Storage Service.
//
// Set the policy from the bucket.
//
// bucketName the bucket name.
//
// policy the bucket policy.
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) SetBucketPolicy(bucketName string, policy string, options ...Option) error {
params := map[string]interface{}{}
params["policy"] = nil
buffer := strings.NewReader(policy)
resp, err := client.do("PUT", bucketName, params, nil, buffer, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
}
// DeleteBucketPolicy API operation for Object Storage Service.
//
// Deletes the policy from the bucket.
//
// bucketName the bucket name.
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) DeleteBucketPolicy(bucketName string, options ...Option) error {
params := map[string]interface{}{}
params["policy"] = nil
resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
}
// SetBucketRequestPayment API operation for Object Storage Service.
//
// Set the requestPayment of bucket
//
// bucketName the bucket name.
//
// paymentConfig the payment configuration
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) SetBucketRequestPayment(bucketName string, paymentConfig RequestPaymentConfiguration, options ...Option) error {
params := map[string]interface{}{}
params["requestPayment"] = nil
var bs []byte
bs, err := xml.Marshal(paymentConfig)
if err != nil {
return err
}
buffer := new(bytes.Buffer)
buffer.Write(bs)
contentType := http.DetectContentType(buffer.Bytes())
headers := map[string]string{}
headers[HTTPHeaderContentType] = contentType
resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
}
// GetBucketRequestPayment API operation for Object Storage Service.
//
// Get bucket requestPayment
//
// bucketName the bucket name.
//
// RequestPaymentConfiguration the payment configuration
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) GetBucketRequestPayment(bucketName string, options ...Option) (RequestPaymentConfiguration, error) {
var out RequestPaymentConfiguration
params := map[string]interface{}{}
params["requestPayment"] = nil
resp, err := client.do("GET", bucketName, params, nil, nil, options...)
if err != nil {
return out, err
}
defer resp.Body.Close()
err = xmlUnmarshal(resp.Body, &out)
return out, err
}
// GetUserQoSInfo API operation for Object Storage Service.
//
// Get user qos.
//
// UserQoSConfiguration the User Qos and range Information.
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) GetUserQoSInfo(options ...Option) (UserQoSConfiguration, error) {
var out UserQoSConfiguration
params := map[string]interface{}{}
params["qosInfo"] = nil
resp, err := client.do("GET", "", params, nil, nil, options...)
if err != nil {
return out, err
}
defer resp.Body.Close()
err = xmlUnmarshal(resp.Body, &out)
return out, err
}
// SetBucketQoSInfo API operation for Object Storage Service.
//
// Set Bucket Qos information.
//
// bucketName the bucket name.
//
// qosConf the qos configuration.
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) SetBucketQoSInfo(bucketName string, qosConf BucketQoSConfiguration, options ...Option) error {
params := map[string]interface{}{}
params["qosInfo"] = nil
var bs []byte
bs, err := xml.Marshal(qosConf)
if err != nil {
return err
}
buffer := new(bytes.Buffer)
buffer.Write(bs)
contentTpye := http.DetectContentType(buffer.Bytes())
headers := map[string]string{}
headers[HTTPHeaderContentType] = contentTpye
resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
}
// GetBucketQosInfo API operation for Object Storage Service.
//
// Get Bucket Qos information.
//
// bucketName the bucket name.
//
// BucketQoSConfiguration the return qos configuration.
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) GetBucketQosInfo(bucketName string, options ...Option) (BucketQoSConfiguration, error) {
var out BucketQoSConfiguration
params := map[string]interface{}{}
params["qosInfo"] = nil
resp, err := client.do("GET", bucketName, params, nil, nil, options...)
if err != nil {
return out, err
}
defer resp.Body.Close()
err = xmlUnmarshal(resp.Body, &out)
return out, err
}
// DeleteBucketQosInfo API operation for Object Storage Service.
//
// Delete Bucket QoS information.
//
// bucketName the bucket name.
//
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) DeleteBucketQosInfo(bucketName string, options ...Option) error {
params := map[string]interface{}{}
params["qosInfo"] = nil
resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
}
// SetBucketInventory API operation for Object Storage Service
//
// Set the Bucket inventory.
//
// bucketName tht bucket name.
//
// inventoryConfig the inventory configuration.
//
// error it's nil if no error, otherwise it's an error.
//
func (client Client) SetBucketInventory(bucketName string, inventoryConfig InventoryConfiguration, options ...Option) error {
params := map[string]interface{}{}
params["inventoryId"] = inventoryConfig.Id
params["inventory"] = nil
var bs []byte
bs, err := xml.Marshal(inventoryConfig)
if err != nil {
return err
}
buffer := new(bytes.Buffer)
buffer.Write(bs)
contentType := http.DetectContentType(buffer.Bytes())
headers := make(map[string]string)
headers[HTTPHeaderContentType] = contentType
resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
}
// GetBucketInventory API operation for Object Storage Service
//
// Get the Bucket inventory.
//
// bucketName tht bucket name.
//
// strInventoryId the inventory id.
//
// InventoryConfiguration the inventory configuration.
//
// error it's nil if no error, otherwise it's an error.
//
func (client Client) GetBucketInventory(bucketName string, strInventoryId string, options ...Option) (InventoryConfiguration, error) {
var out InventoryConfiguration
params := map[string]interface{}{}
params["inventory"] = nil
params["inventoryId"] = strInventoryId
resp, err := client.do("GET", bucketName, params, nil, nil, options...)
if err != nil {
return out, err
}
defer resp.Body.Close()
err = xmlUnmarshal(resp.Body, &out)
return out, err
}
// ListBucketInventory API operation for Object Storage Service
//
// List the Bucket inventory.
//
// bucketName tht bucket name.
//
// continuationToken the users token.
//
// ListInventoryConfigurationsResult list all inventory configuration by .
//
// error it's nil if no error, otherwise it's an error.
//
func (client Client) ListBucketInventory(bucketName, continuationToken string, options ...Option) (ListInventoryConfigurationsResult, error) {
var out ListInventoryConfigurationsResult
params := map[string]interface{}{}
params["inventory"] = nil
if continuationToken == "" {
params["continuation-token"] = nil
} else {
params["continuation-token"] = continuationToken
}
resp, err := client.do("GET", bucketName, params, nil, nil, options...)
if err != nil {
return out, err
}
defer resp.Body.Close()
err = xmlUnmarshal(resp.Body, &out)
return out, err
}
// DeleteBucketInventory API operation for Object Storage Service.
//
// Delete Bucket inventory information.
//
// bucketName tht bucket name.
//
// strInventoryId the inventory id.
//
// error it's nil if no error, otherwise it's an error.
//
func (client Client) DeleteBucketInventory(bucketName, strInventoryId string, options ...Option) error {
params := map[string]interface{}{}
params["inventory"] = nil
params["inventoryId"] = strInventoryId
resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
}
// SetBucketAsyncTask API operation for set async fetch task
//
// bucketName tht bucket name.
//
// asynConf configruation
//
// error it's nil if success, otherwise it's an error.
func (client Client) SetBucketAsyncTask(bucketName string, asynConf AsyncFetchTaskConfiguration, options ...Option) (AsyncFetchTaskResult, error) {
var out AsyncFetchTaskResult
params := map[string]interface{}{}
params["asyncFetch"] = nil
var bs []byte
bs, err := xml.Marshal(asynConf)
if err != nil {
return out, err
}
buffer := new(bytes.Buffer)
buffer.Write(bs)
contentType := http.DetectContentType(buffer.Bytes())
headers := make(map[string]string)
headers[HTTPHeaderContentType] = contentType
resp, err := client.do("POST", bucketName, params, headers, buffer, options...)
if err != nil {
return out, err
}
defer resp.Body.Close()
err = xmlUnmarshal(resp.Body, &out)
return out, err
}
// GetBucketAsyncTask API operation for set async fetch task
//
// bucketName tht bucket name.
//
// taskid returned by SetBucketAsyncTask
//
// error it's nil if success, otherwise it's an error.
func (client Client) GetBucketAsyncTask(bucketName string, taskID string, options ...Option) (AsynFetchTaskInfo, error) {
var out AsynFetchTaskInfo
params := map[string]interface{}{}
params["asyncFetch"] = nil
headers := make(map[string]string)
headers[HTTPHeaderOssTaskID] = taskID
resp, err := client.do("GET", bucketName, params, headers, nil, options...)
if err != nil {
return out, err
}
defer resp.Body.Close()
err = xmlUnmarshal(resp.Body, &out)
return out, err
}
// InitiateBucketWorm creates bucket worm Configuration
// bucketName the bucket name.
// retentionDays the retention period in days
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) InitiateBucketWorm(bucketName string, retentionDays int, options ...Option) (string, error) {
var initiateWormConf InitiateWormConfiguration
initiateWormConf.RetentionPeriodInDays = retentionDays
var respHeader http.Header
isOptSet, _, _ := IsOptionSet(options, responseHeader)
if !isOptSet {
options = append(options, GetResponseHeader(&respHeader))
}
bs, err := xml.Marshal(initiateWormConf)
if err != nil {
return "", err
}
buffer := new(bytes.Buffer)
buffer.Write(bs)
contentType := http.DetectContentType(buffer.Bytes())
headers := make(map[string]string)
headers[HTTPHeaderContentType] = contentType
params := map[string]interface{}{}
params["worm"] = nil
resp, err := client.do("POST", bucketName, params, headers, buffer, options...)
if err != nil {
return "", err
}
defer resp.Body.Close()
respOpt, _ := FindOption(options, responseHeader, nil)
wormID := ""
err = CheckRespCode(resp.StatusCode, []int{http.StatusOK})
if err == nil && respOpt != nil {
wormID = (respOpt.(*http.Header)).Get("x-oss-worm-id")
}
return wormID, err
}
// AbortBucketWorm delete bucket worm Configuration
// bucketName the bucket name.
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) AbortBucketWorm(bucketName string, options ...Option) error {
params := map[string]interface{}{}
params["worm"] = nil
resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
}
// CompleteBucketWorm complete bucket worm Configuration
// bucketName the bucket name.
// wormID the worm id
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) CompleteBucketWorm(bucketName string, wormID string, options ...Option) error {
params := map[string]interface{}{}
params["wormId"] = wormID
resp, err := client.do("POST", bucketName, params, nil, nil, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
}
// ExtendBucketWorm exetend bucket worm Configuration
// bucketName the bucket name.
// retentionDays the retention period in days
// wormID the worm id
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) ExtendBucketWorm(bucketName string, retentionDays int, wormID string, options ...Option) error {
var extendWormConf ExtendWormConfiguration
extendWormConf.RetentionPeriodInDays = retentionDays
bs, err := xml.Marshal(extendWormConf)
if err != nil {
return err
}
buffer := new(bytes.Buffer)
buffer.Write(bs)
contentType := http.DetectContentType(buffer.Bytes())
headers := make(map[string]string)
headers[HTTPHeaderContentType] = contentType
params := map[string]interface{}{}
params["wormId"] = wormID
params["wormExtend"] = nil
resp, err := client.do("POST", bucketName, params, headers, buffer, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
}
// GetBucketWorm get bucket worm Configuration
// bucketName the bucket name.
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) GetBucketWorm(bucketName string, options ...Option) (WormConfiguration, error) {
var out WormConfiguration
params := map[string]interface{}{}
params["worm"] = nil
resp, err := client.do("GET", bucketName, params, nil, nil, options...)
if err != nil {
return out, err
}
defer resp.Body.Close()
err = xmlUnmarshal(resp.Body, &out)
return out, err
}
// SetBucketTransferAcc set bucket transfer acceleration configuration
// bucketName the bucket name.
// accConf bucket transfer acceleration configuration
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) SetBucketTransferAcc(bucketName string, accConf TransferAccConfiguration, options ...Option) error {
bs, err := xml.Marshal(accConf)
if err != nil {
return err
}
buffer := new(bytes.Buffer)
buffer.Write(bs)
contentType := http.DetectContentType(buffer.Bytes())
headers := make(map[string]string)
headers[HTTPHeaderContentType] = contentType
params := map[string]interface{}{}
params["transferAcceleration"] = nil
resp, err := client.do("PUT", bucketName, params, headers, buffer, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
}
// GetBucketTransferAcc get bucket transfer acceleration configuration
// bucketName the bucket name.
// accConf bucket transfer acceleration configuration
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) GetBucketTransferAcc(bucketName string, options ...Option) (TransferAccConfiguration, error) {
var out TransferAccConfiguration
params := map[string]interface{}{}
params["transferAcceleration"] = nil
resp, err := client.do("GET", bucketName, params, nil, nil, options...)
if err != nil {
return out, err
}
defer resp.Body.Close()
err = xmlUnmarshal(resp.Body, &out)
return out, err
}
// DeleteBucketTransferAcc delete bucket transfer acceleration configuration
// bucketName the bucket name.
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) DeleteBucketTransferAcc(bucketName string, options ...Option) error {
params := map[string]interface{}{}
params["transferAcceleration"] = nil
resp, err := client.do("DELETE", bucketName, params, nil, nil, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent})
}
// PutBucketReplication put bucket replication configuration
// bucketName the bucket name.
// xmlBody the replication configuration.
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) PutBucketReplication(bucketName string, xmlBody string, options ...Option) error {
buffer := new(bytes.Buffer)
buffer.Write([]byte(xmlBody))
contentType := http.DetectContentType(buffer.Bytes())
headers := map[string]string{}
headers[HTTPHeaderContentType] = contentType
params := map[string]interface{}{}
params["replication"] = nil
params["comp"] = "add"
resp, err := client.do("POST", bucketName, params, headers, buffer, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
}
// GetBucketReplication get bucket replication configuration
// bucketName the bucket name.
// string the replication configuration.
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) GetBucketReplication(bucketName string, options ...Option) (string, error) {
params := map[string]interface{}{}
params["replication"] = nil
resp, err := client.do("GET", bucketName, params, nil, nil, options...)
if err != nil {
return "", err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(data), err
}
// DeleteBucketReplication delete bucket replication configuration
// bucketName the bucket name.
// ruleId the ID of the replication configuration.
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) DeleteBucketReplication(bucketName string, ruleId string, options ...Option) error {
replicationxml := ReplicationXML{}
replicationxml.ID = ruleId
bs, err := xml.Marshal(replicationxml)
if err != nil {
return err
}
buffer := new(bytes.Buffer)
buffer.Write(bs)
contentType := http.DetectContentType(buffer.Bytes())
headers := map[string]string{}
headers[HTTPHeaderContentType] = contentType
params := map[string]interface{}{}
params["replication"] = nil
params["comp"] = "delete"
resp, err := client.do("POST", bucketName, params, headers, buffer, options...)
if err != nil {
return err
}
defer resp.Body.Close()
return CheckRespCode(resp.StatusCode, []int{http.StatusOK})
}
// GetBucketReplicationLocation get the locations of the target bucket that can be copied to
// bucketName the bucket name.
// string the locations of the target bucket that can be copied to.
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) GetBucketReplicationLocation(bucketName string, options ...Option) (string, error) {
params := map[string]interface{}{}
params["replicationLocation"] = nil
resp, err := client.do("GET", bucketName, params, nil, nil, options...)
if err != nil {
return "", err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(data), err
}
// GetBucketReplicationProgress get the replication progress of bucket
// bucketName the bucket name.
// ruleId the ID of the replication configuration.
// string the replication progress of bucket.
// error it's nil if no error, otherwise it's an error object.
//
func (client Client) GetBucketReplicationProgress(bucketName string, ruleId string, options ...Option) (string, error) {
params := map[string]interface{}{}
params["replicationProgress"] = nil
if ruleId != "" {
params["rule-id"] = ruleId
}
resp, err := client.do("GET", bucketName, params, nil, nil, options...)
if err != nil {
return "", err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(data), err
}
// GetBucketCname get bucket's binding cname
// bucketName the bucket name.
// string the xml configuration of bucket.
// error it's nil if no error, otherwise it's an error object.
func (client Client) GetBucketCname(bucketName string, options ...Option) (string, error) {
params := map[string]interface{}{}
params["cname"] = nil
resp, err := client.do("GET", bucketName, params, nil, nil, options...)
if err != nil {
return "", err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(data), err
}
// LimitUploadSpeed set upload bandwidth limit speed,default is 0,unlimited
// upSpeed KB/s, 0 is unlimited,default is 0
// error it's nil if success, otherwise failure
func (client Client) LimitUploadSpeed(upSpeed int) error {
if client.Config == nil {
return fmt.Errorf("client config is nil")
}
return client.Config.LimitUploadSpeed(upSpeed)
}
// LimitDownloadSpeed set download bandwidth limit speed,default is 0,unlimited
// downSpeed KB/s, 0 is unlimited,default is 0
// error it's nil if success, otherwise failure
func (client Client) LimitDownloadSpeed(downSpeed int) error {
if client.Config == nil {
return fmt.Errorf("client config is nil")
}
return client.Config.LimitDownloadSpeed(downSpeed)
}
// UseCname sets the flag of using CName. By default it's false.
//
// isUseCname true: the endpoint has the CName, false: the endpoint does not have cname. Default is false.
//
func UseCname(isUseCname bool) ClientOption {
return func(client *Client) {
client.Config.IsCname = isUseCname
client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
}
}
// Timeout sets the HTTP timeout in seconds.
//
// connectTimeoutSec HTTP timeout in seconds. Default is 10 seconds. 0 means infinite (not recommended)
// readWriteTimeout HTTP read or write's timeout in seconds. Default is 20 seconds. 0 means infinite.
//
func Timeout(connectTimeoutSec, readWriteTimeout int64) ClientOption {
return func(client *Client) {
client.Config.HTTPTimeout.ConnectTimeout =
time.Second * time.Duration(connectTimeoutSec)
client.Config.HTTPTimeout.ReadWriteTimeout =
time.Second * time.Duration(readWriteTimeout)
client.Config.HTTPTimeout.HeaderTimeout =
time.Second * time.Duration(readWriteTimeout)
client.Config.HTTPTimeout.IdleConnTimeout =
time.Second * time.Duration(readWriteTimeout)
client.Config.HTTPTimeout.LongTimeout =
time.Second * time.Duration(readWriteTimeout*10)
}
}
// SecurityToken sets the temporary user's SecurityToken.
//
// token STS token
//
func SecurityToken(token string) ClientOption {
return func(client *Client) {
client.Config.SecurityToken = strings.TrimSpace(token)
}
}
// EnableMD5 enables MD5 validation.
//
// isEnableMD5 true: enable MD5 validation; false: disable MD5 validation.
//
func EnableMD5(isEnableMD5 bool) ClientOption {
return func(client *Client) {
client.Config.IsEnableMD5 = isEnableMD5
}
}
// MD5ThresholdCalcInMemory sets the memory usage threshold for computing the MD5, default is 16MB.
//
// threshold the memory threshold in bytes. When the uploaded content is more than 16MB, the temp file is used for computing the MD5.
//
func MD5ThresholdCalcInMemory(threshold int64) ClientOption {
return func(client *Client) {
client.Config.MD5Threshold = threshold
}
}
// EnableCRC enables the CRC checksum. Default is true.
//
// isEnableCRC true: enable CRC checksum; false: disable the CRC checksum.
//
func EnableCRC(isEnableCRC bool) ClientOption {
return func(client *Client) {
client.Config.IsEnableCRC = isEnableCRC
}
}
// UserAgent specifies UserAgent. The default is aliyun-sdk-go/1.2.0 (windows/-/amd64;go1.5.2).
//
// userAgent the user agent string.
//
func UserAgent(userAgent string) ClientOption {
return func(client *Client) {
client.Config.UserAgent = userAgent
client.Config.UserSetUa = true
}
}
// Proxy sets the proxy (optional). The default is not using proxy.
//
// proxyHost the proxy host in the format "host:port". For example, proxy.com:80 .
//
func Proxy(proxyHost string) ClientOption {
return func(client *Client) {
client.Config.IsUseProxy = true
client.Config.ProxyHost = proxyHost
client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
}
}
// AuthProxy sets the proxy information with user name and password.
//
// proxyHost the proxy host in the format "host:port". For example, proxy.com:80 .
// proxyUser the proxy user name.
// proxyPassword the proxy password.
//
func AuthProxy(proxyHost, proxyUser, proxyPassword string) ClientOption {
return func(client *Client) {
client.Config.IsUseProxy = true
client.Config.ProxyHost = proxyHost
client.Config.IsAuthProxy = true
client.Config.ProxyUser = proxyUser
client.Config.ProxyPassword = proxyPassword
client.Conn.url.Init(client.Config.Endpoint, client.Config.IsCname, client.Config.IsUseProxy)
}
}
//
// HTTPClient sets the http.Client in use to the one passed in
//
func HTTPClient(HTTPClient *http.Client) ClientOption {
return func(client *Client) {
client.HTTPClient = HTTPClient
}
}
//
// SetLogLevel sets the oss sdk log level
//
func SetLogLevel(LogLevel int) ClientOption {
return func(client *Client) {
client.Config.LogLevel = LogLevel
}
}
//
// SetLogger sets the oss sdk logger
//
func SetLogger(Logger *log.Logger) ClientOption {
return func(client *Client) {
client.Config.Logger = Logger
}
}
// SetCredentialsProvider sets funciton for get the user's ak
func SetCredentialsProvider(provider CredentialsProvider) ClientOption {
return func(client *Client) {
client.Config.CredentialsProvider = provider
}
}
// SetLocalAddr sets funciton for local addr
func SetLocalAddr(localAddr net.Addr) ClientOption {
return func(client *Client) {
client.Config.LocalAddr = localAddr
}
}
// AuthVersion sets auth version: v1 or v2 signature which oss_server needed
func AuthVersion(authVersion AuthVersionType) ClientOption {
return func(client *Client) {
client.Config.AuthVersion = authVersion
}
}
// AdditionalHeaders sets special http headers needed to be signed
func AdditionalHeaders(headers []string) ClientOption {
return func(client *Client) {
client.Config.AdditionalHeaders = headers
}
}
// only effective from go1.7 onward,RedirectEnabled set http redirect enabled or not
func RedirectEnabled(enabled bool) ClientOption {
return func(client *Client) {
client.Config.RedirectEnabled = enabled
}
}
// skip verifying tls certificate file
func InsecureSkipVerify(enabled bool) ClientOption {
return func(client *Client) {
client.Config.InsecureSkipVerify = enabled
}
}
// Private
func (client Client) do(method, bucketName string, params map[string]interface{},
headers map[string]string, data io.Reader, options ...Option) (*Response, error) {
err := CheckBucketName(bucketName)
if len(bucketName) > 0 && err != nil {
return nil, err
}
// option headers
addHeaders := make(map[string]string)
err = handleOptions(addHeaders, options)
if err != nil {
return nil, err
}
// merge header
if headers == nil {
headers = make(map[string]string)
}
for k, v := range addHeaders {
if _, ok := headers[k]; !ok {
headers[k] = v
}
}
resp, err := client.Conn.Do(method, bucketName, "", params, headers, data, 0, nil)
// get response header
respHeader, _ := FindOption(options, responseHeader, nil)
if respHeader != nil {
pRespHeader := respHeader.(*http.Header)
*pRespHeader = resp.Headers
}
return resp, err
}
Go
1
https://gitee.com/cinus/aliyun-oss-go-sdk.git
git@gitee.com:cinus/aliyun-oss-go-sdk.git
cinus
aliyun-oss-go-sdk
aliyun-oss-go-sdk
v2.2.0

搜索帮助