code
stringlengths
11
335k
docstring
stringlengths
20
11.8k
func_name
stringlengths
1
100
language
stringclasses
1 value
repo
stringclasses
245 values
path
stringlengths
4
144
url
stringlengths
43
214
license
stringclasses
4 values
func (s *OssClientSuite) SetUpTest(c *C) { }
SetUpTest runs after each test or benchmark runs
SetUpTest
go
aliyun/aliyun-oss-go-sdk
oss/client_test.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/client_test.go
MIT
func (s *OssClientSuite) TearDownTest(c *C) { }
TearDownTest runs once after all tests or benchmarks have finished running
TearDownTest
go
aliyun/aliyun-oss-go-sdk
oss/client_test.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/client_test.go
MIT
func (bucket Bucket) InitiateMultipartUpload(objectKey string, options ...Option) (InitiateMultipartUploadResult, error) { var imur InitiateMultipartUploadResult opts := AddContentType(options, objectKey) params, _ := GetRawParams(options) paramKeys := []string{"sequential", "withHashContext", "x-oss-enable-md5", "x-oss-enable-sha1", "x-oss-enable-sha256"} ConvertEmptyValueToNil(params, paramKeys) params["uploads"] = nil resp, err := bucket.do("POST", objectKey, params, opts, nil, nil) if err != nil { return imur, err } defer resp.Body.Close() err = xmlUnmarshal(resp.Body, &imur) return imur, err }
InitiateMultipartUpload initializes multipart upload objectKey object name options the object constricts for upload. The valid options are CacheControl, ContentDisposition, ContentEncoding, Expires, ServerSideEncryption, Meta, check out the following link: https://www.alibabacloud.com/help/en/object-storage-service/latest/initiatemultipartupload InitiateMultipartUploadResult the return value of the InitiateMultipartUpload, which is used for calls later on such as UploadPartFromFile,UploadPartCopy. error it's nil if the operation succeeds, otherwise it's an error object.
InitiateMultipartUpload
go
aliyun/aliyun-oss-go-sdk
oss/multipart.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/multipart.go
MIT
func (bucket Bucket) UploadPart(imur InitiateMultipartUploadResult, reader io.Reader, partSize int64, partNumber int, options ...Option) (UploadPart, error) { request := &UploadPartRequest{ InitResult: &imur, Reader: reader, PartSize: partSize, PartNumber: partNumber, } result, err := bucket.DoUploadPart(request, options) return result.Part, err }
UploadPart uploads parts After initializing a Multipart Upload, the upload Id and object key could be used for uploading the parts. Each part has its part number (ranges from 1 to 10,000). And for each upload Id, the part number identifies the position of the part in the whole file. And thus with the same part number and upload Id, another part upload will overwrite the data. Except the last one, minimal part size is 100KB. There's no limit on the last part size. imur the returned value of InitiateMultipartUpload. reader io.Reader the reader for the part's data. size the part size. partNumber the part number (ranges from 1 to 10,000). Invalid part number will lead to InvalidArgument error. UploadPart the return value of the upload part. It consists of PartNumber and ETag. It's valid when error is nil. error it's nil if the operation succeeds, otherwise it's an error object.
UploadPart
go
aliyun/aliyun-oss-go-sdk
oss/multipart.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/multipart.go
MIT
func (bucket Bucket) UploadPartFromFile(imur InitiateMultipartUploadResult, filePath string, startPosition, partSize int64, partNumber int, options ...Option) (UploadPart, error) { var part = UploadPart{} fd, err := os.Open(filePath) if err != nil { return part, err } defer fd.Close() fd.Seek(startPosition, os.SEEK_SET) request := &UploadPartRequest{ InitResult: &imur, Reader: fd, PartSize: partSize, PartNumber: partNumber, } result, err := bucket.DoUploadPart(request, options) return result.Part, err }
UploadPartFromFile uploads part from the file. imur the return value of a successful InitiateMultipartUpload. filePath the local file path to upload. startPosition the start position in the local file. partSize the part size. partNumber the part number (from 1 to 10,000) UploadPart the return value consists of PartNumber and ETag. error it's nil if the operation succeeds, otherwise it's an error object.
UploadPartFromFile
go
aliyun/aliyun-oss-go-sdk
oss/multipart.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/multipart.go
MIT
func (bucket Bucket) DoUploadPart(request *UploadPartRequest, options []Option) (*UploadPartResult, error) { listener := GetProgressListener(options) options = append(options, ContentLength(request.PartSize)) params := map[string]interface{}{} params["partNumber"] = strconv.Itoa(request.PartNumber) params["uploadId"] = request.InitResult.UploadID resp, err := bucket.do("PUT", request.InitResult.Key, params, options, &io.LimitedReader{R: request.Reader, N: request.PartSize}, listener) if err != nil { return &UploadPartResult{}, err } defer resp.Body.Close() part := UploadPart{ ETag: resp.Headers.Get(HTTPHeaderEtag), PartNumber: request.PartNumber, } if bucket.GetConfig().IsEnableCRC { err = CheckCRC(resp, "DoUploadPart") if err != nil { return &UploadPartResult{part}, err } } return &UploadPartResult{part}, nil }
DoUploadPart does the actual part upload. request part upload request UploadPartResult the result of uploading part. error it's nil if the operation succeeds, otherwise it's an error object.
DoUploadPart
go
aliyun/aliyun-oss-go-sdk
oss/multipart.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/multipart.go
MIT
func (bucket Bucket) UploadPartCopy(imur InitiateMultipartUploadResult, srcBucketName, srcObjectKey string, startPosition, partSize int64, partNumber int, options ...Option) (UploadPart, error) { var out UploadPartCopyResult var part UploadPart var opts []Option //first find version id versionIdKey := "versionId" versionId, _ := FindOption(options, versionIdKey, nil) if versionId == nil { opts = []Option{CopySource(srcBucketName, url.QueryEscape(srcObjectKey)), CopySourceRange(startPosition, partSize)} } else { opts = []Option{CopySourceVersion(srcBucketName, url.QueryEscape(srcObjectKey), versionId.(string)), CopySourceRange(startPosition, partSize)} options = DeleteOption(options, versionIdKey) } opts = append(opts, options...) params := map[string]interface{}{} params["partNumber"] = strconv.Itoa(partNumber) params["uploadId"] = imur.UploadID resp, err := bucket.do("PUT", imur.Key, params, opts, nil, nil) if err != nil { return part, err } defer resp.Body.Close() err = xmlUnmarshal(resp.Body, &out) if err != nil { return part, err } part.ETag = out.ETag part.PartNumber = partNumber return part, nil }
UploadPartCopy uploads part copy imur the return value of InitiateMultipartUpload copySrc source Object name startPosition the part's start index in the source file partSize the part size partNumber the part number, ranges from 1 to 10,000. If it exceeds the range OSS returns InvalidArgument error. options the constraints of source object for the copy. The copy happens only when these contraints are met. Otherwise it returns error. CopySourceIfNoneMatch, CopySourceIfModifiedSince CopySourceIfUnmodifiedSince, check out the following link for the detail https://www.alibabacloud.com/help/en/object-storage-service/latest/uploadpartcopy UploadPart the return value consists of PartNumber and ETag. error it's nil if the operation succeeds, otherwise it's an error object.
UploadPartCopy
go
aliyun/aliyun-oss-go-sdk
oss/multipart.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/multipart.go
MIT
func (bucket Bucket) CompleteMultipartUpload(imur InitiateMultipartUploadResult, parts []UploadPart, options ...Option) (CompleteMultipartUploadResult, error) { var out CompleteMultipartUploadResult sort.Sort(UploadParts(parts)) cxml := completeMultipartUploadXML{} cxml.Part = parts bs, err := xml.Marshal(cxml) if err != nil { return out, err } buffer := new(bytes.Buffer) buffer.Write(bs) params := map[string]interface{}{} params["uploadId"] = imur.UploadID resp, err := bucket.do("POST", imur.Key, params, options, buffer, nil) if err != nil { return out, err } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return out, err } err = CheckRespCode(resp.StatusCode, []int{http.StatusOK}) if len(body) > 0 { if err != nil { err = tryConvertServiceError(body, resp, err) } else { callback, _ := FindOption(options, HTTPHeaderOssCallback, nil) if callback == nil { err = xml.Unmarshal(body, &out) } else { rb, _ := FindOption(options, responseBody, nil) if rb != nil { if rbody, ok := rb.(*[]byte); ok { *rbody = body } } } } } return out, err }
CompleteMultipartUpload completes the multipart upload. imur the return value of InitiateMultipartUpload. parts the array of return value of UploadPart/UploadPartFromFile/UploadPartCopy. CompleteMultipartUploadResponse the return value when the call succeeds. Only valid when the error is nil. error it's nil if the operation succeeds, otherwise it's an error object.
CompleteMultipartUpload
go
aliyun/aliyun-oss-go-sdk
oss/multipart.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/multipart.go
MIT
func (bucket Bucket) AbortMultipartUpload(imur InitiateMultipartUploadResult, options ...Option) error { params := map[string]interface{}{} params["uploadId"] = imur.UploadID resp, err := bucket.do("DELETE", imur.Key, params, options, nil, nil) if err != nil { return err } defer resp.Body.Close() return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent}) }
AbortMultipartUpload aborts the multipart upload. imur the return value of InitiateMultipartUpload. error it's nil if the operation succeeds, otherwise it's an error object.
AbortMultipartUpload
go
aliyun/aliyun-oss-go-sdk
oss/multipart.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/multipart.go
MIT
func (bucket Bucket) ListUploadedParts(imur InitiateMultipartUploadResult, options ...Option) (ListUploadedPartsResult, error) { var out ListUploadedPartsResult options = append(options, EncodingType("url")) params := map[string]interface{}{} params, err := GetRawParams(options) if err != nil { return out, err } params["uploadId"] = imur.UploadID resp, err := bucket.do("GET", imur.Key, params, options, nil, nil) if err != nil { return out, err } defer resp.Body.Close() err = xmlUnmarshal(resp.Body, &out) if err != nil { return out, err } err = decodeListUploadedPartsResult(&out) return out, err }
ListUploadedParts lists the uploaded parts. imur the return value of InitiateMultipartUpload. ListUploadedPartsResponse the return value if it succeeds, only valid when error is nil. error it's nil if the operation succeeds, otherwise it's an error object.
ListUploadedParts
go
aliyun/aliyun-oss-go-sdk
oss/multipart.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/multipart.go
MIT
func (bucket Bucket) ListMultipartUploads(options ...Option) (ListMultipartUploadResult, error) { var out ListMultipartUploadResult options = append(options, EncodingType("url")) params, err := GetRawParams(options) if err != nil { return out, err } params["uploads"] = nil resp, err := bucket.doInner("GET", "", params, options, nil, nil) if err != nil { return out, err } defer resp.Body.Close() err = xmlUnmarshal(resp.Body, &out) if err != nil { return out, err } err = decodeListMultipartUploadResult(&out) return out, err }
ListMultipartUploads lists all ongoing multipart upload tasks options listObject's filter. Prefix specifies the returned object's prefix; KeyMarker specifies the returned object's start point in lexicographic order; MaxKeys specifies the max entries to return; Delimiter is the character for grouping object keys. ListMultipartUploadResponse the return value if it succeeds, only valid when error is nil. error it's nil if the operation succeeds, otherwise it's an error object.
ListMultipartUploads
go
aliyun/aliyun-oss-go-sdk
oss/multipart.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/multipart.go
MIT
func (conn *Conn) init(config *Config, urlMaker *urlMaker, client *http.Client) error { if client == nil { // New transport transport := newTransport(conn, config) // Proxy if conn.config.IsUseProxy { proxyURL, err := url.Parse(config.ProxyHost) if err != nil { return err } if config.IsAuthProxy { if config.ProxyPassword != "" { proxyURL.User = url.UserPassword(config.ProxyUser, config.ProxyPassword) } else { proxyURL.User = url.User(config.ProxyUser) } } transport.Proxy = http.ProxyURL(proxyURL) } client = &http.Client{Transport: transport} if !config.RedirectEnabled { disableHTTPRedirect(client) } } conn.config = config conn.url = urlMaker conn.client = client return nil }
init initializes Conn
init
go
aliyun/aliyun-oss-go-sdk
oss/conn.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/conn.go
MIT
func (conn Conn) Do(method, bucketName, objectName string, params map[string]interface{}, headers map[string]string, data io.Reader, initCRC uint64, listener ProgressListener) (*Response, error) { return conn.DoWithContext(nil, method, bucketName, objectName, params, headers, data, initCRC, listener) }
Do sends request and returns the response
Do
go
aliyun/aliyun-oss-go-sdk
oss/conn.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/conn.go
MIT
func (conn Conn) DoWithContext(ctx context.Context, method, bucketName, objectName string, params map[string]interface{}, headers map[string]string, data io.Reader, initCRC uint64, listener ProgressListener) (*Response, error) { urlParams := conn.getURLParams(params) subResource := conn.getSubResource(params) uri := conn.url.getURL(bucketName, objectName, urlParams) resource := "" if conn.config.AuthVersion != AuthV4 { resource = conn.getResource(bucketName, objectName, subResource) } else { resource = conn.getResourceV4(bucketName, objectName, subResource) } return conn.doRequest(ctx, method, uri, resource, headers, data, initCRC, listener) }
DoWithContext sends request and returns the response with context
DoWithContext
go
aliyun/aliyun-oss-go-sdk
oss/conn.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/conn.go
MIT
func (conn Conn) DoURL(method HTTPMethod, signedURL string, headers map[string]string, data io.Reader, initCRC uint64, listener ProgressListener) (*Response, error) { return conn.DoURLWithContext(nil, method, signedURL, headers, data, initCRC, listener) }
DoURL sends the request with signed URL and returns the response result.
DoURL
go
aliyun/aliyun-oss-go-sdk
oss/conn.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/conn.go
MIT
func (conn Conn) DoURLWithContext(ctx context.Context, method HTTPMethod, signedURL string, headers map[string]string, data io.Reader, initCRC uint64, listener ProgressListener) (*Response, error) { // Get URI from signedURL uri, err := url.ParseRequestURI(signedURL) if err != nil { return nil, err } m := strings.ToUpper(string(method)) req := &http.Request{ Method: m, URL: uri, Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Header: make(http.Header), Host: uri.Host, } if ctx != nil { req = req.WithContext(ctx) } tracker := &readerTracker{completedBytes: 0} fd, crc := conn.handleBody(req, data, initCRC, listener, tracker) if fd != nil { defer func() { fd.Close() os.Remove(fd.Name()) }() } if conn.config.IsAuthProxy { auth := conn.config.ProxyUser + ":" + conn.config.ProxyPassword basic := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth)) req.Header.Set("Proxy-Authorization", basic) } req.Header.Set(HTTPHeaderHost, req.Host) req.Header.Set(HTTPHeaderUserAgent, conn.config.UserAgent) if headers != nil { for k, v := range headers { req.Header.Set(k, v) } } // Transfer started event := newProgressEvent(TransferStartedEvent, 0, req.ContentLength, 0) publishProgress(listener, event) if conn.config.LogLevel >= Debug { conn.LoggerHTTPReq(req) } resp, err := conn.client.Do(req) if err != nil { // Transfer failed conn.config.WriteLog(Debug, "[Resp:%p]http error:%s\n", req, err.Error()) event = newProgressEvent(TransferFailedEvent, tracker.completedBytes, req.ContentLength, 0) publishProgress(listener, event) return nil, err } if conn.config.LogLevel >= Debug { //print out http resp conn.LoggerHTTPResp(req, resp) } // Transfer completed event = newProgressEvent(TransferCompletedEvent, tracker.completedBytes, req.ContentLength, 0) publishProgress(listener, event) return conn.handleResponse(resp, crc) }
DoURLWithContext sends the request with signed URL and context and returns the response result.
DoURLWithContext
go
aliyun/aliyun-oss-go-sdk
oss/conn.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/conn.go
MIT
func (conn Conn) getResource(bucketName, objectName, subResource string) string { if subResource != "" { subResource = "?" + subResource } if bucketName == "" { if conn.config.AuthVersion == AuthV2 { return url.QueryEscape("/") + subResource } return fmt.Sprintf("/%s%s", bucketName, subResource) } if conn.config.AuthVersion == AuthV2 { return url.QueryEscape("/"+bucketName+"/") + strings.Replace(url.QueryEscape(objectName), "+", "%20", -1) + subResource } return fmt.Sprintf("/%s/%s%s", bucketName, objectName, subResource) }
getResource gets canonicalized resource
getResource
go
aliyun/aliyun-oss-go-sdk
oss/conn.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/conn.go
MIT
func (conn Conn) getResourceV4(bucketName, objectName, subResource string) string { if subResource != "" { subResource = "?" + subResource } if bucketName == "" { return fmt.Sprintf("/%s", subResource) } if objectName != "" { objectName = url.QueryEscape(objectName) objectName = strings.Replace(objectName, "+", "%20", -1) objectName = strings.Replace(objectName, "%2F", "/", -1) return fmt.Sprintf("/%s/%s%s", bucketName, objectName, subResource) } return fmt.Sprintf("/%s/%s", bucketName, subResource) }
getResource gets canonicalized resource
getResourceV4
go
aliyun/aliyun-oss-go-sdk
oss/conn.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/conn.go
MIT
func (conn Conn) handleBody(req *http.Request, body io.Reader, initCRC uint64, listener ProgressListener, tracker *readerTracker) (*os.File, hash.Hash64) { var file *os.File var crc hash.Hash64 reader := body readerLen, err := GetReaderLen(reader) if err == nil { req.ContentLength = readerLen } req.Header.Set(HTTPHeaderContentLength, strconv.FormatInt(req.ContentLength, 10)) // MD5 if body != nil && conn.config.IsEnableMD5 && req.Header.Get(HTTPHeaderContentMD5) == "" { md5 := "" reader, md5, file, _ = calcMD5(body, req.ContentLength, conn.config.MD5Threshold) req.Header.Set(HTTPHeaderContentMD5, md5) } // CRC if reader != nil && conn.config.IsEnableCRC { crc = NewCRC(CrcTable(), initCRC) reader = TeeReader(reader, crc, req.ContentLength, listener, tracker) } // HTTP body rc, ok := reader.(io.ReadCloser) if !ok && reader != nil { rc = ioutil.NopCloser(reader) } if conn.isUploadLimitReq(req) { limitReader := &LimitSpeedReader{ reader: rc, ossLimiter: conn.config.UploadLimiter, } req.Body = limitReader } else { req.Body = rc } return file, crc }
handleBody handles request body
handleBody
go
aliyun/aliyun-oss-go-sdk
oss/conn.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/conn.go
MIT
func (conn Conn) isUploadLimitReq(req *http.Request) bool { if conn.config.UploadLimitSpeed == 0 || conn.config.UploadLimiter == nil { return false } if req.Method != "GET" && req.Method != "DELETE" && req.Method != "HEAD" { if req.ContentLength > 0 { return true } } return false }
isUploadLimitReq: judge limit upload speed or not
isUploadLimitReq
go
aliyun/aliyun-oss-go-sdk
oss/conn.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/conn.go
MIT
func (conn Conn) handleResponse(resp *http.Response, crc hash.Hash64) (*Response, error) { var cliCRC uint64 var srvCRC uint64 statusCode := resp.StatusCode if statusCode/100 != 2 { if statusCode >= 400 && statusCode <= 505 { // 4xx and 5xx indicate that the operation has error occurred var respBody []byte var errorXml []byte respBody, err := readResponseBody(resp) if err != nil { return nil, err } errorXml = respBody if len(respBody) == 0 && len(resp.Header.Get(HTTPHeaderOssErr)) > 0 { errorXml, err = base64.StdEncoding.DecodeString(resp.Header.Get(HTTPHeaderOssErr)) if err != nil { errorXml = respBody } } if len(errorXml) == 0 { err = ServiceError{ StatusCode: statusCode, RequestID: resp.Header.Get(HTTPHeaderOssRequestID), Ec: resp.Header.Get(HTTPHeaderOssEc), } } else { srvErr, errIn := serviceErrFromXML(errorXml, resp.StatusCode, resp.Header.Get(HTTPHeaderOssRequestID)) if errIn != nil { // error unmarshal the error response if len(resp.Header.Get(HTTPHeaderOssEc)) > 0 { err = fmt.Errorf("oss: service returned invalid response body, status = %s, RequestId = %s, ec = %s", resp.Status, resp.Header.Get(HTTPHeaderOssRequestID), resp.Header.Get(HTTPHeaderOssEc)) } else { err = fmt.Errorf("oss: service returned invalid response body, status = %s, RequestId = %s", resp.Status, resp.Header.Get(HTTPHeaderOssRequestID)) } } else { err = srvErr } } return &Response{ StatusCode: resp.StatusCode, Headers: resp.Header, Body: ioutil.NopCloser(bytes.NewReader(respBody)), // restore the body }, err } else if statusCode >= 300 && statusCode <= 307 { // OSS use 3xx, but response has no body err := fmt.Errorf("oss: service returned %d,%s", resp.StatusCode, resp.Status) return &Response{ StatusCode: resp.StatusCode, Headers: resp.Header, Body: resp.Body, }, err } else { // (0,300) [308,400) [506,) // Other extended http StatusCode var respBody []byte var errorXml []byte respBody, err := readResponseBody(resp) if err != nil { return &Response{StatusCode: resp.StatusCode, Headers: resp.Header, Body: ioutil.NopCloser(bytes.NewReader(respBody))}, err } errorXml = respBody if len(respBody) == 0 && len(resp.Header.Get(HTTPHeaderOssErr)) > 0 { errorXml, err = base64.StdEncoding.DecodeString(resp.Header.Get(HTTPHeaderOssErr)) if err != nil { errorXml = respBody } } if len(errorXml) == 0 { err = ServiceError{ StatusCode: statusCode, RequestID: resp.Header.Get(HTTPHeaderOssRequestID), Ec: resp.Header.Get(HTTPHeaderOssEc), } } else { srvErr, errIn := serviceErrFromXML(errorXml, resp.StatusCode, resp.Header.Get(HTTPHeaderOssRequestID)) if errIn != nil { // error unmarshal the error response if len(resp.Header.Get(HTTPHeaderOssEc)) > 0 { err = fmt.Errorf("unknown response body, status = %s, RequestId = %s, ec = %s", resp.Status, resp.Header.Get(HTTPHeaderOssRequestID), resp.Header.Get(HTTPHeaderOssEc)) } else { err = fmt.Errorf("unknown response body, status = %s, RequestId = %s", resp.Status, resp.Header.Get(HTTPHeaderOssRequestID)) } } else { err = srvErr } } return &Response{ StatusCode: resp.StatusCode, Headers: resp.Header, Body: ioutil.NopCloser(bytes.NewReader(respBody)), // restore the body }, err } } else { if conn.config.IsEnableCRC && crc != nil { cliCRC = crc.Sum64() } srvCRC, _ = strconv.ParseUint(resp.Header.Get(HTTPHeaderOssCRC64), 10, 64) realBody := resp.Body if conn.isDownloadLimitResponse(resp) { limitReader := &LimitSpeedReader{ reader: realBody, ossLimiter: conn.config.DownloadLimiter, } realBody = limitReader } // 2xx, successful return &Response{ StatusCode: resp.StatusCode, Headers: resp.Header, Body: realBody, ClientCRC: cliCRC, ServerCRC: srvCRC, }, nil } }
handleResponse handles response
handleResponse
go
aliyun/aliyun-oss-go-sdk
oss/conn.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/conn.go
MIT
func (conn Conn) isDownloadLimitResponse(resp *http.Response) bool { if resp == nil || conn.config.DownloadLimitSpeed == 0 || conn.config.DownloadLimiter == nil { return false } if strings.EqualFold(resp.Request.Method, "GET") { return true } return false }
isUploadLimitReq: judge limit upload speed or not
isDownloadLimitResponse
go
aliyun/aliyun-oss-go-sdk
oss/conn.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/conn.go
MIT
func (conn Conn) LoggerHTTPReq(req *http.Request) { var logBuffer bytes.Buffer logBuffer.WriteString(fmt.Sprintf("[Req:%p]Method:%s\t", req, req.Method)) logBuffer.WriteString(fmt.Sprintf("Host:%s\t", req.URL.Host)) logBuffer.WriteString(fmt.Sprintf("Path:%s\t", req.URL.Path)) logBuffer.WriteString(fmt.Sprintf("Query:%s\t", req.URL.RawQuery)) logBuffer.WriteString(fmt.Sprintf("Header info:")) for k, v := range req.Header { var valueBuffer bytes.Buffer for j := 0; j < len(v); j++ { if j > 0 { valueBuffer.WriteString(" ") } valueBuffer.WriteString(v[j]) } logBuffer.WriteString(fmt.Sprintf("\t%s:%s", k, valueBuffer.String())) } conn.config.WriteLog(Debug, "%s\n", logBuffer.String()) }
LoggerHTTPReq Print the header information of the http request
LoggerHTTPReq
go
aliyun/aliyun-oss-go-sdk
oss/conn.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/conn.go
MIT
func (conn Conn) LoggerHTTPResp(req *http.Request, resp *http.Response) { var logBuffer bytes.Buffer logBuffer.WriteString(fmt.Sprintf("[Resp:%p]StatusCode:%d\t", req, resp.StatusCode)) logBuffer.WriteString(fmt.Sprintf("Header info:")) for k, v := range resp.Header { var valueBuffer bytes.Buffer for j := 0; j < len(v); j++ { if j > 0 { valueBuffer.WriteString(" ") } valueBuffer.WriteString(v[j]) } logBuffer.WriteString(fmt.Sprintf("\t%s:%s", k, valueBuffer.String())) } conn.config.WriteLog(Debug, "%s\n", logBuffer.String()) }
LoggerHTTPResp Print Response to http request
LoggerHTTPResp
go
aliyun/aliyun-oss-go-sdk
oss/conn.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/conn.go
MIT
func (um *urlMaker) Init(endpoint string, isCname bool, isProxy bool) error { return um.InitExt(endpoint, isCname, isProxy, false) }
Init parses endpoint
Init
go
aliyun/aliyun-oss-go-sdk
oss/conn.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/conn.go
MIT
func (um *urlMaker) InitExt(endpoint string, isCname bool, isProxy bool, isPathStyle bool) error { if strings.HasPrefix(endpoint, "http://") { um.Scheme = "http" um.NetLoc = endpoint[len("http://"):] } else if strings.HasPrefix(endpoint, "https://") { um.Scheme = "https" um.NetLoc = endpoint[len("https://"):] } else { um.Scheme = "http" um.NetLoc = endpoint } //use url.Parse() to get real host strUrl := um.Scheme + "://" + um.NetLoc url, err := url.Parse(strUrl) if err != nil { return err } um.NetLoc = url.Host host, _, err := net.SplitHostPort(um.NetLoc) if err != nil { host = um.NetLoc if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' { host = host[1 : len(host)-1] } } ip := net.ParseIP(host) if ip != nil { um.Type = urlTypeIP } else if isCname { um.Type = urlTypeCname } else if isPathStyle { um.Type = urlTypePathStyle } else { um.Type = urlTypeAliyun } um.IsProxy = isProxy return nil }
InitExt parses endpoint
InitExt
go
aliyun/aliyun-oss-go-sdk
oss/conn.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/conn.go
MIT
func (um urlMaker) getSignURL(bucket, object, params string) string { host, path := um.buildURL(bucket, object) return fmt.Sprintf("%s://%s%s?%s", um.Scheme, host, path, params) }
getSignURL gets sign URL
getSignURL
go
aliyun/aliyun-oss-go-sdk
oss/conn.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/conn.go
MIT
func (um urlMaker) getSignRtmpURL(bucket, channelName, params string) string { host, path := um.buildURL(bucket, "live") channelName = url.QueryEscape(channelName) channelName = strings.Replace(channelName, "+", "%20", -1) return fmt.Sprintf("rtmp://%s%s/%s?%s", host, path, channelName, params) }
getSignRtmpURL Build Sign Rtmp URL
getSignRtmpURL
go
aliyun/aliyun-oss-go-sdk
oss/conn.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/conn.go
MIT
func (e ServiceError) Error() string { errorStr := fmt.Sprintf("oss: service returned error: StatusCode=%d, ErrorCode=%s, ErrorMessage=\"%s\", RequestId=%s", e.StatusCode, e.Code, e.Message, e.RequestID) if len(e.Endpoint) > 0 { errorStr = fmt.Sprintf("%s, Endpoint=%s", errorStr, e.Endpoint) } if len(e.Ec) > 0 { errorStr = fmt.Sprintf("%s, Ec=%s", errorStr, e.Ec) } return errorStr }
Error implements interface error
Error
go
aliyun/aliyun-oss-go-sdk
oss/error.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/error.go
MIT
func (e UnexpectedStatusCodeError) Error() string { s := func(i int) string { return fmt.Sprintf("%d %s", i, http.StatusText(i)) } got := s(e.got) expected := []string{} for _, v := range e.allowed { expected = append(expected, s(v)) } return fmt.Sprintf("oss: status code from service response is %s; was expecting %s", got, strings.Join(expected, " or ")) }
Error implements interface error
Error
go
aliyun/aliyun-oss-go-sdk
oss/error.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/error.go
MIT
func (e UnexpectedStatusCodeError) Got() int { return e.got }
Got is the actual status code returned by oss.
Got
go
aliyun/aliyun-oss-go-sdk
oss/error.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/error.go
MIT
func CheckRespCode(respCode int, allowed []int) error { for _, v := range allowed { if respCode == v { return nil } } return UnexpectedStatusCodeError{allowed, respCode} }
CheckRespCode returns UnexpectedStatusError if the given response code is not one of the allowed status codes; otherwise nil.
CheckRespCode
go
aliyun/aliyun-oss-go-sdk
oss/error.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/error.go
MIT
func CheckCallbackResp(resp *Response) error { var err error contentLengthStr := resp.Headers.Get("Content-Length") contentLength, _ := strconv.Atoi(contentLengthStr) var bodyBytes []byte if contentLength > 0 { bodyBytes, _ = ioutil.ReadAll(resp.Body) } if len(bodyBytes) > 0 { srvErr, errIn := serviceErrFromXML(bodyBytes, resp.StatusCode, resp.Headers.Get(HTTPHeaderOssRequestID)) if errIn != nil { if len(resp.Headers.Get(HTTPHeaderOssEc)) > 0 { err = fmt.Errorf("unknown response body, status code = %d, RequestId = %s, ec = %s", resp.StatusCode, resp.Headers.Get(HTTPHeaderOssRequestID), resp.Headers.Get(HTTPHeaderOssEc)) } else { err = fmt.Errorf("unknown response body, status code= %d, RequestId = %s", resp.StatusCode, resp.Headers.Get(HTTPHeaderOssRequestID)) } } else { err = srvErr } } return err }
CheckCallbackResp return error if the given response code is not 200
CheckCallbackResp
go
aliyun/aliyun-oss-go-sdk
oss/error.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/error.go
MIT
func (e CRCCheckError) Error() string { return fmt.Sprintf("oss: the crc of %s is inconsistent, client %d but server %d; request id is %s", e.operation, e.clientCRC, e.serverCRC, e.requestID) }
Error implements interface error
Error
go
aliyun/aliyun-oss-go-sdk
oss/error.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/error.go
MIT
func (bucket Bucket) PutObject(objectKey string, reader io.Reader, options ...Option) error { opts := AddContentType(options, objectKey) request := &PutObjectRequest{ ObjectKey: objectKey, Reader: reader, } resp, err := bucket.DoPutObject(request, opts) if err != nil { return err } defer resp.Body.Close() return err }
PutObject creates a new object and it will overwrite the original one if it exists already. objectKey the object key in UTF-8 encoding. The length must be between 1 and 1023, and cannot start with "/" or "\". reader io.Reader instance for reading the data for uploading options the options for uploading the object. The valid options here are CacheControl, ContentDisposition, ContentEncoding Expires, ServerSideEncryption, ObjectACL and Meta. Refer to the link below for more details. https://www.alibabacloud.com/help/en/object-storage-service/latest/putobject error it's nil if no error, otherwise it's an error object.
PutObject
go
aliyun/aliyun-oss-go-sdk
oss/bucket.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/bucket.go
MIT
func (bucket Bucket) PutObjectFromFile(objectKey, filePath string, options ...Option) error { fd, err := os.Open(filePath) if err != nil { return err } defer fd.Close() opts := AddContentType(options, filePath, objectKey) request := &PutObjectRequest{ ObjectKey: objectKey, Reader: fd, } resp, err := bucket.DoPutObject(request, opts) if err != nil { return err } defer resp.Body.Close() return err }
PutObjectFromFile creates a new object from the local file. objectKey object key. filePath the local file path to upload. options the options for uploading the object. Refer to the parameter options in PutObject for more details. error it's nil if no error, otherwise it's an error object.
PutObjectFromFile
go
aliyun/aliyun-oss-go-sdk
oss/bucket.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/bucket.go
MIT
func (bucket Bucket) DoPutObject(request *PutObjectRequest, options []Option) (*Response, error) { isOptSet, _, _ := IsOptionSet(options, HTTPHeaderContentType) if !isOptSet { options = AddContentType(options, request.ObjectKey) } listener := GetProgressListener(options) params := map[string]interface{}{} resp, err := bucket.do("PUT", request.ObjectKey, params, options, request.Reader, listener) if err != nil { return nil, err } if bucket.GetConfig().IsEnableCRC { err = CheckCRC(resp, "DoPutObject") if err != nil { return resp, err } } err = CheckRespCode(resp.StatusCode, []int{http.StatusOK}) body, _ := ioutil.ReadAll(resp.Body) if len(body) > 0 { if err != nil { err = tryConvertServiceError(body, resp, err) } else { rb, _ := FindOption(options, responseBody, nil) if rb != nil { if rbody, ok := rb.(*[]byte); ok { *rbody = body } } } } return resp, err }
DoPutObject does the actual upload work. request the request instance for uploading an object. options the options for uploading an object. Response the response from OSS. error it's nil if no error, otherwise it's an error object.
DoPutObject
go
aliyun/aliyun-oss-go-sdk
oss/bucket.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/bucket.go
MIT
func (bucket Bucket) GetObject(objectKey string, options ...Option) (io.ReadCloser, error) { result, err := bucket.DoGetObject(&GetObjectRequest{objectKey}, options) if err != nil { return nil, err } return result.Response, nil }
GetObject downloads the object. objectKey the object key. options the options for downloading the object. The valid values are: Range, IfModifiedSince, IfUnmodifiedSince, IfMatch, IfNoneMatch, AcceptEncoding. For more details, please check out: https://www.alibabacloud.com/help/en/object-storage-service/latest/getobject io.ReadCloser reader instance for reading data from response. It must be called close() after the usage and only valid when error is nil. error it's nil if no error, otherwise it's an error object.
GetObject
go
aliyun/aliyun-oss-go-sdk
oss/bucket.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/bucket.go
MIT
func (bucket Bucket) GetObjectToFile(objectKey, filePath string, options ...Option) error { tempFilePath := filePath + TempFileSuffix // Calls the API to actually download the object. Returns the result instance. result, err := bucket.DoGetObject(&GetObjectRequest{objectKey}, options) if err != nil { return err } defer result.Response.Close() // If the local file does not exist, create a new one. If it exists, overwrite it. fd, err := os.OpenFile(tempFilePath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, FilePermMode) if err != nil { return err } // Copy the data to the local file path. _, err = io.Copy(fd, result.Response.Body) fd.Close() if err != nil { return err } // Compares the CRC value hasRange, _, _ := IsOptionSet(options, HTTPHeaderRange) encodeOpt, _ := FindOption(options, HTTPHeaderAcceptEncoding, nil) acceptEncoding := "" if encodeOpt != nil { acceptEncoding = encodeOpt.(string) } if bucket.GetConfig().IsEnableCRC && !hasRange && acceptEncoding != "gzip" { result.Response.ClientCRC = result.ClientCRC.Sum64() err = CheckCRC(result.Response, "GetObjectToFile") if err != nil { os.Remove(tempFilePath) return err } } return os.Rename(tempFilePath, filePath) }
GetObjectToFile downloads the data to a local file. objectKey the object key to download. filePath the local file to store the object data. options the options for downloading the object. Refer to the parameter options in method GetObject for more details. error it's nil if no error, otherwise it's an error object.
GetObjectToFile
go
aliyun/aliyun-oss-go-sdk
oss/bucket.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/bucket.go
MIT
func (bucket Bucket) DoGetObject(request *GetObjectRequest, options []Option) (*GetObjectResult, error) { params, _ := GetRawParams(options) resp, err := bucket.do("GET", request.ObjectKey, params, options, nil, nil) if err != nil { return nil, err } result := &GetObjectResult{ Response: resp, } // CRC var crcCalc hash.Hash64 hasRange, _, _ := IsOptionSet(options, HTTPHeaderRange) if bucket.GetConfig().IsEnableCRC && !hasRange { crcCalc = crc64.New(CrcTable()) result.ServerCRC = resp.ServerCRC result.ClientCRC = crcCalc } // Progress listener := GetProgressListener(options) contentLen, _ := strconv.ParseInt(resp.Headers.Get(HTTPHeaderContentLength), 10, 64) resp.Body = TeeReader(resp.Body, crcCalc, contentLen, listener, nil) return result, nil }
DoGetObject is the actual API that gets the object. It's the internal function called by other public APIs. request the request to download the object. options the options for downloading the file. Checks out the parameter options in method GetObject. GetObjectResult the result instance of getting the object. error it's nil if no error, otherwise it's an error object.
DoGetObject
go
aliyun/aliyun-oss-go-sdk
oss/bucket.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/bucket.go
MIT
func (bucket Bucket) CopyObject(srcObjectKey, destObjectKey string, options ...Option) (CopyObjectResult, error) { var out CopyObjectResult //first find version id versionIdKey := "versionId" versionId, _ := FindOption(options, versionIdKey, nil) if versionId == nil { options = append(options, CopySource(bucket.BucketName, url.QueryEscape(srcObjectKey))) } else { options = DeleteOption(options, versionIdKey) options = append(options, CopySourceVersion(bucket.BucketName, url.QueryEscape(srcObjectKey), versionId.(string))) } params := map[string]interface{}{} resp, err := bucket.do("PUT", destObjectKey, params, options, nil, nil) if err != nil { return out, err } defer resp.Body.Close() err = xmlUnmarshal(resp.Body, &out) return out, err }
CopyObject copies the object inside the bucket. srcObjectKey the source object to copy. destObjectKey the target object to copy. options options for copying an object. You can specify the conditions of copy. The valid conditions are CopySourceIfMatch, CopySourceIfNoneMatch, CopySourceIfModifiedSince, CopySourceIfUnmodifiedSince, MetadataDirective. Also you can specify the target object's attributes, such as CacheControl, ContentDisposition, ContentEncoding, Expires, ServerSideEncryption, ObjectACL, Meta. Refer to the link below for more details : https://www.alibabacloud.com/help/en/object-storage-service/latest/copyobject error it's nil if no error, otherwise it's an error object.
CopyObject
go
aliyun/aliyun-oss-go-sdk
oss/bucket.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/bucket.go
MIT
func (bucket Bucket) CopyObjectTo(destBucketName, destObjectKey, srcObjectKey string, options ...Option) (CopyObjectResult, error) { return bucket.copy(srcObjectKey, destBucketName, destObjectKey, options...) }
CopyObjectTo copies the object to another bucket. srcObjectKey source object key. The source bucket is Bucket.BucketName . destBucketName target bucket name. destObjectKey target object name. options copy options, check out parameter options in function CopyObject for more details. error it's nil if no error, otherwise it's an error object.
CopyObjectTo
go
aliyun/aliyun-oss-go-sdk
oss/bucket.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/bucket.go
MIT
func (bucket Bucket) CopyObjectFrom(srcBucketName, srcObjectKey, destObjectKey string, options ...Option) (CopyObjectResult, error) { destBucketName := bucket.BucketName var out CopyObjectResult srcBucket, err := bucket.Client.Bucket(srcBucketName) if err != nil { return out, err } return srcBucket.copy(srcObjectKey, destBucketName, destObjectKey, options...) }
CopyObjectFrom copies the object to another bucket. srcBucketName source bucket name. srcObjectKey source object name. destObjectKey target object name. The target bucket name is Bucket.BucketName. options copy options. Check out parameter options in function CopyObject. error it's nil if no error, otherwise it's an error object.
CopyObjectFrom
go
aliyun/aliyun-oss-go-sdk
oss/bucket.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/bucket.go
MIT
func (bucket Bucket) AppendObject(objectKey string, reader io.Reader, appendPosition int64, options ...Option) (int64, error) { request := &AppendObjectRequest{ ObjectKey: objectKey, Reader: reader, Position: appendPosition, } result, err := bucket.DoAppendObject(request, options) if err != nil { return appendPosition, err } return result.NextPosition, err }
AppendObject uploads the data in the way of appending an existing or new object. AppendObject the parameter appendPosition specifies which postion (in the target object) to append. For the first append (to a non-existing file), the appendPosition should be 0. The appendPosition in the subsequent calls will be the current object length. For example, the first appendObject's appendPosition is 0 and it uploaded 65536 bytes data, then the second call's position is 65536. The response header x-oss-next-append-position after each successful request also specifies the next call's append position (so the caller need not to maintain this information). objectKey the target object to append to. reader io.Reader. The read instance for reading the data to append. appendPosition the start position to append. destObjectProperties the options for the first appending, such as CacheControl, ContentDisposition, ContentEncoding, Expires, ServerSideEncryption, ObjectACL. int64 the next append position, it's valid when error is nil. error it's nil if no error, otherwise it's an error object.
AppendObject
go
aliyun/aliyun-oss-go-sdk
oss/bucket.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/bucket.go
MIT
func (bucket Bucket) DoAppendObject(request *AppendObjectRequest, options []Option) (*AppendObjectResult, error) { params := map[string]interface{}{} params["append"] = nil params["position"] = strconv.FormatInt(request.Position, 10) headers := make(map[string]string) opts := AddContentType(options, request.ObjectKey) handleOptions(headers, opts) var initCRC uint64 isCRCSet, initCRCOpt, _ := IsOptionSet(options, initCRC64) if isCRCSet { initCRC = initCRCOpt.(uint64) } listener := GetProgressListener(options) handleOptions(headers, opts) ctxArg, _ := FindOption(options, contextArg, nil) ctx, _ := ctxArg.(context.Context) resp, err := bucket.Client.Conn.DoWithContext(ctx, "POST", bucket.BucketName, request.ObjectKey, params, headers, request.Reader, initCRC, listener) // get response header respHeader, _ := FindOption(options, responseHeader, nil) if respHeader != nil { pRespHeader := respHeader.(*http.Header) if resp != nil { *pRespHeader = resp.Headers } } if err != nil { return nil, err } defer resp.Body.Close() nextPosition, _ := strconv.ParseInt(resp.Headers.Get(HTTPHeaderOssNextAppendPosition), 10, 64) result := &AppendObjectResult{ NextPosition: nextPosition, CRC: resp.ServerCRC, } if bucket.GetConfig().IsEnableCRC && isCRCSet { err = CheckCRC(resp, "AppendObject") if err != nil { return result, err } } return result, nil }
DoAppendObject is the actual API that does the object append. request the request object for appending object. options the options for appending object. AppendObjectResult the result object for appending object. error it's nil if no error, otherwise it's an error object.
DoAppendObject
go
aliyun/aliyun-oss-go-sdk
oss/bucket.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/bucket.go
MIT
func (bucket Bucket) DeleteObject(objectKey string, options ...Option) error { params, _ := GetRawParams(options) resp, err := bucket.do("DELETE", objectKey, params, options, nil, nil) if err != nil { return err } defer resp.Body.Close() return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent}) }
DeleteObject deletes the object. objectKey the object key to delete. error it's nil if no error, otherwise it's an error object.
DeleteObject
go
aliyun/aliyun-oss-go-sdk
oss/bucket.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/bucket.go
MIT
func (bucket Bucket) DeleteObjects(objectKeys []string, options ...Option) (DeleteObjectsResult, error) { out := DeleteObjectsResult{} dxml := deleteXML{} for _, key := range objectKeys { dxml.Objects = append(dxml.Objects, DeleteObject{Key: key}) } isQuiet, _ := FindOption(options, deleteObjectsQuiet, false) dxml.Quiet = isQuiet.(bool) xmlData := marshalDeleteObjectToXml(dxml) body, err := bucket.DeleteMultipleObjectsXml(xmlData, options...) if err != nil { return out, err } deletedResult := DeleteObjectVersionsResult{} if !dxml.Quiet { if err = xmlUnmarshal(strings.NewReader(body), &deletedResult); err == nil { err = decodeDeleteObjectsResult(&deletedResult) } } // Keep compatibility:need convert to struct DeleteObjectsResult out.XMLName = deletedResult.XMLName for _, v := range deletedResult.DeletedObjectsDetail { out.DeletedObjects = append(out.DeletedObjects, v.Key) } return out, err }
DeleteObjects deletes multiple objects. objectKeys the object keys to delete. options the options for deleting objects. Supported option is DeleteObjectsQuiet which means it will not return error even deletion failed (not recommended). By default it's not used. DeleteObjectsResult the result object. error it's nil if no error, otherwise it's an error object.
DeleteObjects
go
aliyun/aliyun-oss-go-sdk
oss/bucket.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/bucket.go
MIT
func (bucket Bucket) DeleteObjectVersions(objectVersions []DeleteObject, options ...Option) (DeleteObjectVersionsResult, error) { out := DeleteObjectVersionsResult{} dxml := deleteXML{} dxml.Objects = objectVersions isQuiet, _ := FindOption(options, deleteObjectsQuiet, false) dxml.Quiet = isQuiet.(bool) xmlData := marshalDeleteObjectToXml(dxml) body, err := bucket.DeleteMultipleObjectsXml(xmlData, options...) if err != nil { return out, err } if !dxml.Quiet { if err = xmlUnmarshal(strings.NewReader(body), &out); err == nil { err = decodeDeleteObjectsResult(&out) } } return out, err }
DeleteObjectVersions deletes multiple object versions. objectVersions the object keys and versions to delete. options the options for deleting objects. Supported option is DeleteObjectsQuiet which means it will not return error even deletion failed (not recommended). By default it's not used. DeleteObjectVersionsResult the result object. error it's nil if no error, otherwise it's an error object.
DeleteObjectVersions
go
aliyun/aliyun-oss-go-sdk
oss/bucket.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/bucket.go
MIT
func (bucket Bucket) DeleteMultipleObjectsXml(xmlData string, options ...Option) (string, error) { buffer := new(bytes.Buffer) bs := []byte(xmlData) buffer.Write(bs) options = append(options, ContentType("application/xml")) sum := md5.Sum(bs) b64 := base64.StdEncoding.EncodeToString(sum[:]) options = append(options, ContentMD5(b64)) params := map[string]interface{}{} params["delete"] = nil params["encoding-type"] = "url" resp, err := bucket.doInner("POST", "", params, options, buffer, nil) if err != nil { return "", err } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) out := string(body) return out, err }
DeleteMultipleObjectsXml deletes multiple object or deletes multiple object versions. xmlData the object keys and versions to delete as the xml format. options the options for deleting objects. string the result response body. error it's nil if no error, otherwise it's an error.
DeleteMultipleObjectsXml
go
aliyun/aliyun-oss-go-sdk
oss/bucket.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/bucket.go
MIT
func (bucket Bucket) IsObjectExist(objectKey string, options ...Option) (bool, error) { _, err := bucket.GetObjectMeta(objectKey, options...) if err == nil { return true, nil } switch err.(type) { case ServiceError: if err.(ServiceError).StatusCode == 404 { return false, nil } }
IsObjectExist checks if the object exists. bool flag of object's existence (true:exists; false:non-exist) when error is nil. error it's nil if no error, otherwise it's an error object.
IsObjectExist
go
aliyun/aliyun-oss-go-sdk
oss/bucket.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/bucket.go
MIT
func (s *OssDownloadSuite) SetUpSuite(c *C) { bucketName := bucketNamePrefix + RandLowStr(6) if cloudboxControlEndpoint == "" { client, err := New(endpoint, accessID, accessKey) c.Assert(err, IsNil) s.client = client s.client.CreateBucket(bucketName) bucket, err := s.client.Bucket(bucketName) c.Assert(err, IsNil) s.bucket = bucket testLogger.Println("test crc started") } else { client, err := New(cloudboxEndpoint, accessID, accessKey) c.Assert(err, IsNil) s.client = client controlClient, err := New(cloudboxControlEndpoint, accessID, accessKey) c.Assert(err, IsNil) s.cloudBoxControlClient = controlClient controlClient.CreateBucket(bucketName) bucket, err := s.client.Bucket(bucketName) c.Assert(err, IsNil) s.bucket = bucket } testLogger.Println("test download started") }
SetUpSuite runs once when the suite starts running
SetUpSuite
go
aliyun/aliyun-oss-go-sdk
oss/download_test.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/download_test.go
MIT
func (s *OssDownloadSuite) TearDownSuite(c *C) { // Delete part keyMarker := KeyMarker("") uploadIDMarker := UploadIDMarker("") for { lmur, err := s.bucket.ListMultipartUploads(keyMarker, uploadIDMarker) c.Assert(err, IsNil) for _, upload := range lmur.Uploads { var imur = InitiateMultipartUploadResult{Bucket: s.bucket.BucketName, Key: upload.Key, UploadID: upload.UploadID} err = s.bucket.AbortMultipartUpload(imur) c.Assert(err, IsNil) } keyMarker = KeyMarker(lmur.NextKeyMarker) uploadIDMarker = UploadIDMarker(lmur.NextUploadIDMarker) if !lmur.IsTruncated { break } } // Delete objects marker := Marker("") for { lor, err := s.bucket.ListObjects(marker) c.Assert(err, IsNil) for _, object := range lor.Objects { err = s.bucket.DeleteObject(object.Key) c.Assert(err, IsNil) } marker = Marker(lor.NextMarker) if !lor.IsTruncated { break } } // Delete bucket if s.cloudBoxControlClient != nil { err := s.cloudBoxControlClient.DeleteBucket(s.bucket.BucketName) c.Assert(err, IsNil) } else { err := s.client.DeleteBucket(s.bucket.BucketName) c.Assert(err, IsNil) } testLogger.Println("test download completed") }
TearDownSuite runs before each test or benchmark starts running
TearDownSuite
go
aliyun/aliyun-oss-go-sdk
oss/download_test.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/download_test.go
MIT
func (s *OssDownloadSuite) SetUpTest(c *C) { err := removeTempFiles("../oss", ".jpg") c.Assert(err, IsNil) }
SetUpTest runs after each test or benchmark runs
SetUpTest
go
aliyun/aliyun-oss-go-sdk
oss/download_test.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/download_test.go
MIT
func (s *OssDownloadSuite) TearDownTest(c *C) { err := removeTempFiles("../oss", ".jpg") c.Assert(err, IsNil) err = removeTempFiles("../oss", ".temp") c.Assert(err, IsNil) }
TearDownTest runs once after all tests or benchmarks have finished running
TearDownTest
go
aliyun/aliyun-oss-go-sdk
oss/download_test.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/download_test.go
MIT
func DownErrorHooker(part downloadPart) error { if part.Index == 4 { time.Sleep(time.Second) return fmt.Errorf("ErrorHooker") } return nil }
DownErrorHooker requests hook by downloadPart
DownErrorHooker
go
aliyun/aliyun-oss-go-sdk
oss/download_test.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/download_test.go
MIT
func compareFilesWithRange(fileL string, offsetL int64, fileR string, offsetR int64, size int64) (bool, error) { finL, err := os.Open(fileL) if err != nil { return false, err } defer finL.Close() finL.Seek(offsetL, os.SEEK_SET) finR, err := os.Open(fileR) if err != nil { return false, err } defer finR.Close() finR.Seek(offsetR, os.SEEK_SET) statL, err := finL.Stat() if err != nil { return false, err } statR, err := finR.Stat() if err != nil { return false, err } if (offsetL+size > statL.Size()) || (offsetR+size > statR.Size()) { return false, nil } part := statL.Size() - offsetL if part > 16*1024 { part = 16 * 1024 } bufL := make([]byte, part) bufR := make([]byte, part) for readN := int64(0); readN < size; { n, _ := finL.Read(bufL) if 0 == n { break } n, _ = finR.Read(bufR) if 0 == n { break } tailer := part if tailer > size-readN { tailer = size - readN } readN += tailer if !bytes.Equal(bufL[0:tailer], bufR[0:tailer]) { return false, nil } } return true, nil }
compareFilesWithRange compares the content between fileL and fileR with specified range
compareFilesWithRange
go
aliyun/aliyun-oss-go-sdk
oss/download_test.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/download_test.go
MIT
func TypeByExtension(filePath string) string { typ := mime.TypeByExtension(path.Ext(filePath)) if typ == "" { typ = extToMimeType[strings.ToLower(path.Ext(filePath))] } else { if strings.HasPrefix(typ, "text/") && strings.Contains(typ, "charset=") { typ = removeCharsetInMimeType(typ) } } return typ }
TypeByExtension returns the MIME type associated with the file extension ext. gets the file's MIME type for HTTP header Content-Type
TypeByExtension
go
aliyun/aliyun-oss-go-sdk
oss/mime.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/mime.go
MIT
func removeCharsetInMimeType(typ string) (str string) { temArr := strings.Split(typ, ";") var builder strings.Builder for i, s := range temArr { tmpStr := strings.Trim(s, " ") if strings.Contains(tmpStr, "charset=") { continue } if i == 0 { builder.WriteString(s) } else { builder.WriteString("; " + s) } } return builder.String() }
Remove charset from mime type
removeCharsetInMimeType
go
aliyun/aliyun-oss-go-sdk
oss/mime.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/mime.go
MIT
func (s *OssCrcSuite) SetUpSuite(c *C) { bucketName = bucketNamePrefix + RandLowStr(6) if cloudboxControlEndpoint == "" { client, err := New(endpoint, accessID, accessKey) c.Assert(err, IsNil) s.client = client s.client.CreateBucket(bucketName) bucket, err := s.client.Bucket(bucketName) c.Assert(err, IsNil) s.bucket = bucket testLogger.Println("test crc started") } else { client, err := New(cloudboxEndpoint, accessID, accessKey) c.Assert(err, IsNil) s.client = client controlClient, err := New(cloudboxControlEndpoint, accessID, accessKey) c.Assert(err, IsNil) s.cloudBoxControlClient = controlClient controlClient.CreateBucket(bucketName) bucket, err := s.client.Bucket(bucketName) c.Assert(err, IsNil) s.bucket = bucket } }
SetUpSuite runs once when the suite starts running
SetUpSuite
go
aliyun/aliyun-oss-go-sdk
oss/crc_test.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crc_test.go
MIT
func (s *OssCrcSuite) TearDownSuite(c *C) { // Delete part keyMarker := KeyMarker("") uploadIDMarker := UploadIDMarker("") for { lmur, err := s.bucket.ListMultipartUploads(keyMarker, uploadIDMarker) c.Assert(err, IsNil) for _, upload := range lmur.Uploads { var imur = InitiateMultipartUploadResult{Bucket: s.bucket.BucketName, Key: upload.Key, UploadID: upload.UploadID} err = s.bucket.AbortMultipartUpload(imur) c.Assert(err, IsNil) } keyMarker = KeyMarker(lmur.NextKeyMarker) uploadIDMarker = UploadIDMarker(lmur.NextUploadIDMarker) if !lmur.IsTruncated { break } } // Delete objects marker := Marker("") for { lor, err := s.bucket.ListObjects(marker) c.Assert(err, IsNil) for _, object := range lor.Objects { err = s.bucket.DeleteObject(object.Key) c.Assert(err, IsNil) } marker = Marker(lor.NextMarker) if !lor.IsTruncated { break } } // Delete bucket if s.cloudBoxControlClient != nil { err := s.cloudBoxControlClient.DeleteBucket(s.bucket.BucketName) c.Assert(err, IsNil) } else { err := s.client.DeleteBucket(s.bucket.BucketName) c.Assert(err, IsNil) } testLogger.Println("test crc completed") }
TearDownSuite runs before each test or benchmark starts running
TearDownSuite
go
aliyun/aliyun-oss-go-sdk
oss/crc_test.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crc_test.go
MIT
func (s *OssCrcSuite) SetUpTest(c *C) { err := removeTempFiles("../oss", ".jpg") c.Assert(err, IsNil) }
SetUpTest runs after each test or benchmark runs
SetUpTest
go
aliyun/aliyun-oss-go-sdk
oss/crc_test.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crc_test.go
MIT
func (s *OssCrcSuite) TearDownTest(c *C) { err := removeTempFiles("../oss", ".jpg") c.Assert(err, IsNil) }
TearDownTest runs once after all tests or benchmarks have finished running
TearDownTest
go
aliyun/aliyun-oss-go-sdk
oss/crc_test.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crc_test.go
MIT
func testCRC64Combine(c *C, str string, pos int, crc uint64) { tabECMA := crc64.MakeTable(crc64.ECMA) // Test CRC64 hash := crc64.New(tabECMA) io.WriteString(hash, str) crc1 := hash.Sum64() c.Assert(crc1, Equals, crc) // Test CRC64 combine hash = crc64.New(tabECMA) io.WriteString(hash, str[0:pos]) crc1 = hash.Sum64() hash = crc64.New(tabECMA) io.WriteString(hash, str[pos:len(str)]) crc2 := hash.Sum64() crc1 = CRC64Combine(crc1, crc2, uint64(len(str)-pos)) c.Assert(crc1, Equals, crc) }
testCRC64Combine tests CRC64 on vector[0..pos] which should have CRC64 crc. Also test CRC64Combine on vector[] split in two.
testCRC64Combine
go
aliyun/aliyun-oss-go-sdk
oss/crc_test.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crc_test.go
MIT
func (bucket Bucket) CreateLiveChannel(channelName string, config LiveChannelConfiguration) (CreateLiveChannelResult, error) { var out CreateLiveChannelResult bs, err := xml.Marshal(config) if err != nil { return out, err } buffer := new(bytes.Buffer) buffer.Write(bs) params := map[string]interface{}{} params["live"] = nil resp, err := bucket.do("PUT", channelName, params, nil, buffer, nil) if err != nil { return out, err } defer resp.Body.Close() err = xmlUnmarshal(resp.Body, &out) return out, err }
CreateLiveChannel create a live-channel channelName the name of the channel config configuration of the channel CreateLiveChannelResult the result of create live-channel error nil if success, otherwise error
CreateLiveChannel
go
aliyun/aliyun-oss-go-sdk
oss/livechannel.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/livechannel.go
MIT
func (bucket Bucket) PutLiveChannelStatus(channelName, status string) error { params := map[string]interface{}{} params["live"] = nil params["status"] = status resp, err := bucket.do("PUT", channelName, params, nil, nil, nil) if err != nil { return err } defer resp.Body.Close() return CheckRespCode(resp.StatusCode, []int{http.StatusOK}) }
PutLiveChannelStatus Set the status of the live-channel: enabled/disabled channelName the name of the channel status enabled/disabled error nil if success, otherwise error
PutLiveChannelStatus
go
aliyun/aliyun-oss-go-sdk
oss/livechannel.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/livechannel.go
MIT
func (bucket Bucket) PostVodPlaylist(channelName, playlistName string, startTime, endTime time.Time) error { params := map[string]interface{}{} params["vod"] = nil params["startTime"] = strconv.FormatInt(startTime.Unix(), 10) params["endTime"] = strconv.FormatInt(endTime.Unix(), 10) key := fmt.Sprintf("%s/%s", channelName, playlistName) resp, err := bucket.do("POST", key, params, nil, nil, nil) if err != nil { return err } defer resp.Body.Close() return CheckRespCode(resp.StatusCode, []int{http.StatusOK}) }
PostVodPlaylist create an playlist based on the specified playlist name, startTime and endTime channelName the name of the channel playlistName the name of the playlist, must end with ".m3u8" startTime the start time of the playlist endTime the endtime of the playlist error nil if success, otherwise error
PostVodPlaylist
go
aliyun/aliyun-oss-go-sdk
oss/livechannel.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/livechannel.go
MIT
func (bucket Bucket) GetVodPlaylist(channelName string, startTime, endTime time.Time) (io.ReadCloser, error) { params := map[string]interface{}{} params["vod"] = nil params["startTime"] = strconv.FormatInt(startTime.Unix(), 10) params["endTime"] = strconv.FormatInt(endTime.Unix(), 10) resp, err := bucket.do("GET", channelName, params, nil, nil, nil) if err != nil { return nil, err } return resp.Body, nil }
GetVodPlaylist get the playlist based on the specified channelName, startTime and endTime channelName the name of the channel startTime the start time of the playlist endTime the endtime of the playlist io.ReadCloser reader instance for reading data from response. It must be called close() after the usage and only valid when error is nil. error nil if success, otherwise error
GetVodPlaylist
go
aliyun/aliyun-oss-go-sdk
oss/livechannel.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/livechannel.go
MIT
func (bucket Bucket) GetLiveChannelStat(channelName string) (LiveChannelStat, error) { var out LiveChannelStat params := map[string]interface{}{} params["live"] = nil params["comp"] = "stat" resp, err := bucket.do("GET", channelName, params, nil, nil, nil) if err != nil { return out, err } defer resp.Body.Close() err = xmlUnmarshal(resp.Body, &out) return out, err }
GetLiveChannelStat Get the state of the live-channel channelName the name of the channel LiveChannelStat the state of the live-channel error nil if success, otherwise error
GetLiveChannelStat
go
aliyun/aliyun-oss-go-sdk
oss/livechannel.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/livechannel.go
MIT
func (bucket Bucket) GetLiveChannelInfo(channelName string) (LiveChannelConfiguration, error) { var out LiveChannelConfiguration params := map[string]interface{}{} params["live"] = nil resp, err := bucket.do("GET", channelName, params, nil, nil, nil) if err != nil { return out, err } defer resp.Body.Close() err = xmlUnmarshal(resp.Body, &out) return out, err }
GetLiveChannelInfo Get the configuration info of the live-channel channelName the name of the channel LiveChannelConfiguration the configuration info of the live-channel error nil if success, otherwise error
GetLiveChannelInfo
go
aliyun/aliyun-oss-go-sdk
oss/livechannel.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/livechannel.go
MIT
func (bucket Bucket) GetLiveChannelHistory(channelName string) (LiveChannelHistory, error) { var out LiveChannelHistory params := map[string]interface{}{} params["live"] = nil params["comp"] = "history" resp, err := bucket.do("GET", channelName, params, nil, nil, nil) if err != nil { return out, err } defer resp.Body.Close() err = xmlUnmarshal(resp.Body, &out) return out, err }
GetLiveChannelHistory Get push records of live-channel channelName the name of the channel LiveChannelHistory push records error nil if success, otherwise error
GetLiveChannelHistory
go
aliyun/aliyun-oss-go-sdk
oss/livechannel.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/livechannel.go
MIT
func (bucket Bucket) ListLiveChannel(options ...Option) (ListLiveChannelResult, error) { var out ListLiveChannelResult params, err := GetRawParams(options) if err != nil { return out, err } params["live"] = nil resp, err := bucket.doInner("GET", "", params, nil, nil, nil) if err != nil { return out, err } defer resp.Body.Close() err = xmlUnmarshal(resp.Body, &out) return out, err }
ListLiveChannel list the live-channels options Prefix: filter by the name start with the value of "Prefix" MaxKeys: the maximum count returned Marker: cursor from which starting list ListLiveChannelResult live-channel list error nil if success, otherwise error
ListLiveChannel
go
aliyun/aliyun-oss-go-sdk
oss/livechannel.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/livechannel.go
MIT
func (bucket Bucket) DeleteLiveChannel(channelName string) error { params := map[string]interface{}{} params["live"] = nil if channelName == "" { return fmt.Errorf("invalid argument: channel name is empty") } resp, err := bucket.do("DELETE", channelName, params, nil, nil, nil) if err != nil { return err } defer resp.Body.Close() return CheckRespCode(resp.StatusCode, []int{http.StatusNoContent}) }
DeleteLiveChannel Delete the live-channel. When a client trying to stream the live-channel, the operation will fail. it will only delete the live-channel itself and the object generated by the live-channel will not be deleted. channelName the name of the channel error nil if success, otherwise error
DeleteLiveChannel
go
aliyun/aliyun-oss-go-sdk
oss/livechannel.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/livechannel.go
MIT
func (bucket Bucket) SignRtmpURL(channelName, playlistName string, expires int64) (string, error) { if expires <= 0 { return "", fmt.Errorf("invalid argument: %d, expires must greater than 0", expires) } expiration := time.Now().Unix() + expires return bucket.Client.Conn.signRtmpURL(bucket.BucketName, channelName, playlistName, expiration), nil }
SignRtmpURL Generate a RTMP push-stream signature URL for the trusted user to push the RTMP stream to the live-channel. channelName the name of the channel playlistName the name of the playlist, must end with ".m3u8" expires expiration (in seconds) string singed rtmp push stream url error nil if success, otherwise error
SignRtmpURL
go
aliyun/aliyun-oss-go-sdk
oss/livechannel.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/livechannel.go
MIT
func (sr *SelectObjectResponse) Close() error { return sr.Body.Close() }
Close http reponse body
Close
go
aliyun/aliyun-oss-go-sdk
oss/select_object_type.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/select_object_type.go
MIT
func (sr *SelectObjectResponse) readFrames(p []byte) (int, error) { var nn int var err error var checkValid bool if sr.Frame.OutputRawData == true { nn, err = sr.Body.Read(p) return nn, err } if sr.Finish { return 0, io.EOF } for { // if this Frame is Readed, then not reading Header if sr.Frame.OpenLine != true { err = sr.analysisHeader() if err != nil { return nn, err } } if sr.Frame.FrameType == DataFrameType { n, err := sr.analysisData(p[nn:]) if err != nil { return nn, err } nn += n // if this Frame is readed all data, then empty the Frame to read it with next frame if sr.Frame.ConsumedBytesLength == sr.Frame.PayloadLength-8 { checkValid, err = sr.checkPayloadSum() if err != nil || !checkValid { return nn, fmt.Errorf("%s", err.Error()) } sr.emptyFrame() } if nn == len(p) { return nn, nil } } else if sr.Frame.FrameType == ContinuousFrameType { checkValid, err = sr.checkPayloadSum() if err != nil || !checkValid { return nn, fmt.Errorf("%s", err.Error()) } sr.Frame.OpenLine = false } else if sr.Frame.FrameType == EndFrameType { err = sr.analysisEndFrame() if err != nil { return nn, err } checkValid, err = sr.checkPayloadSum() if checkValid { sr.Finish = true } return nn, err } else if sr.Frame.FrameType == MetaEndFrameCSVType { err = sr.analysisMetaEndFrameCSV() if err != nil { return nn, err } checkValid, err = sr.checkPayloadSum() if checkValid { sr.Finish = true } return nn, err } else if sr.Frame.FrameType == MetaEndFrameJSONType { err = sr.analysisMetaEndFrameJSON() if err != nil { return nn, err } checkValid, err = sr.checkPayloadSum() if checkValid { sr.Finish = true } return nn, err } } return nn, nil }
readFrames is read Frame
readFrames
go
aliyun/aliyun-oss-go-sdk
oss/select_object_type.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/select_object_type.go
MIT
func (sr *SelectObjectResponse) analysisHeader() error { headFrameByte := make([]byte, 20) _, err := sr.readLen(headFrameByte, time.Duration(sr.ReadTimeOut)) if err != nil { return fmt.Errorf("requestId: %s, Read response frame header failure,err:%s", sr.Headers.Get(HTTPHeaderOssRequestID), err.Error()) } frameTypeByte := headFrameByte[0:4] sr.Frame.Version = frameTypeByte[0] frameTypeByte[0] = 0 bytesToInt(frameTypeByte, &sr.Frame.FrameType) if sr.Frame.FrameType != DataFrameType && sr.Frame.FrameType != ContinuousFrameType && sr.Frame.FrameType != EndFrameType && sr.Frame.FrameType != MetaEndFrameCSVType && sr.Frame.FrameType != MetaEndFrameJSONType { return fmt.Errorf("requestId: %s, Unexpected frame type: %d", sr.Headers.Get(HTTPHeaderOssRequestID), sr.Frame.FrameType) } payloadLengthByte := headFrameByte[4:8] bytesToInt(payloadLengthByte, &sr.Frame.PayloadLength) headCheckSumByte := headFrameByte[8:12] bytesToInt(headCheckSumByte, &sr.Frame.HeaderCheckSum) byteOffset := headFrameByte[12:20] bytesToInt(byteOffset, &sr.Frame.Offset) sr.Frame.OpenLine = true err = sr.writerCheckCrc32(byteOffset) return err }
analysisHeader is reading selectObject response body's header
analysisHeader
go
aliyun/aliyun-oss-go-sdk
oss/select_object_type.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/select_object_type.go
MIT
func (sr *SelectObjectResponse) analysisData(p []byte) (int, error) { var needReadLength int32 lenP := int32(len(p)) restByteLength := sr.Frame.PayloadLength - 8 - sr.Frame.ConsumedBytesLength if lenP <= restByteLength { needReadLength = lenP } else { needReadLength = restByteLength } n, err := sr.readLen(p[:needReadLength], time.Duration(sr.ReadTimeOut)) if err != nil { return n, fmt.Errorf("read frame data error,%s", err.Error()) } sr.Frame.ConsumedBytesLength += int32(n) err = sr.writerCheckCrc32(p[:n]) return n, err }
analysisData is reading the DataFrameType data of selectObject response body
analysisData
go
aliyun/aliyun-oss-go-sdk
oss/select_object_type.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/select_object_type.go
MIT
func (sr *SelectObjectResponse) analysisEndFrame() error { var eF EndFrame payLoadBytes := make([]byte, sr.Frame.PayloadLength-8) _, err := sr.readLen(payLoadBytes, time.Duration(sr.ReadTimeOut)) if err != nil { return fmt.Errorf("read end frame error:%s", err.Error()) } bytesToInt(payLoadBytes[0:8], &eF.TotalScanned) bytesToInt(payLoadBytes[8:12], &eF.HTTPStatusCode) errMsgLength := sr.Frame.PayloadLength - 20 eF.ErrorMsg = string(payLoadBytes[12 : errMsgLength+12]) sr.Frame.EndFrame.TotalScanned = eF.TotalScanned sr.Frame.EndFrame.HTTPStatusCode = eF.HTTPStatusCode sr.Frame.EndFrame.ErrorMsg = eF.ErrorMsg err = sr.writerCheckCrc32(payLoadBytes) return err }
analysisEndFrame is reading the EndFrameType data of selectObject response body
analysisEndFrame
go
aliyun/aliyun-oss-go-sdk
oss/select_object_type.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/select_object_type.go
MIT
func (sr *SelectObjectResponse) analysisMetaEndFrameCSV() error { var mCF MetaEndFrameCSV payLoadBytes := make([]byte, sr.Frame.PayloadLength-8) _, err := sr.readLen(payLoadBytes, time.Duration(sr.ReadTimeOut)) if err != nil { return fmt.Errorf("read meta end csv frame error:%s", err.Error()) } bytesToInt(payLoadBytes[0:8], &mCF.TotalScanned) bytesToInt(payLoadBytes[8:12], &mCF.Status) bytesToInt(payLoadBytes[12:16], &mCF.SplitsCount) bytesToInt(payLoadBytes[16:24], &mCF.RowsCount) bytesToInt(payLoadBytes[24:28], &mCF.ColumnsCount) errMsgLength := sr.Frame.PayloadLength - 36 mCF.ErrorMsg = string(payLoadBytes[28 : errMsgLength+28]) sr.Frame.MetaEndFrameCSV.ErrorMsg = mCF.ErrorMsg sr.Frame.MetaEndFrameCSV.TotalScanned = mCF.TotalScanned sr.Frame.MetaEndFrameCSV.Status = mCF.Status sr.Frame.MetaEndFrameCSV.SplitsCount = mCF.SplitsCount sr.Frame.MetaEndFrameCSV.RowsCount = mCF.RowsCount sr.Frame.MetaEndFrameCSV.ColumnsCount = mCF.ColumnsCount err = sr.writerCheckCrc32(payLoadBytes) return err }
analysisMetaEndFrameCSV is reading the MetaEndFrameCSVType data of selectObject response body
analysisMetaEndFrameCSV
go
aliyun/aliyun-oss-go-sdk
oss/select_object_type.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/select_object_type.go
MIT
func (sr *SelectObjectResponse) analysisMetaEndFrameJSON() error { var mJF MetaEndFrameJSON payLoadBytes := make([]byte, sr.Frame.PayloadLength-8) _, err := sr.readLen(payLoadBytes, time.Duration(sr.ReadTimeOut)) if err != nil { return fmt.Errorf("read meta end json frame error:%s", err.Error()) } bytesToInt(payLoadBytes[0:8], &mJF.TotalScanned) bytesToInt(payLoadBytes[8:12], &mJF.Status) bytesToInt(payLoadBytes[12:16], &mJF.SplitsCount) bytesToInt(payLoadBytes[16:24], &mJF.RowsCount) errMsgLength := sr.Frame.PayloadLength - 32 mJF.ErrorMsg = string(payLoadBytes[24 : errMsgLength+24]) sr.Frame.MetaEndFrameJSON.ErrorMsg = mJF.ErrorMsg sr.Frame.MetaEndFrameJSON.TotalScanned = mJF.TotalScanned sr.Frame.MetaEndFrameJSON.Status = mJF.Status sr.Frame.MetaEndFrameJSON.SplitsCount = mJF.SplitsCount sr.Frame.MetaEndFrameJSON.RowsCount = mJF.RowsCount err = sr.writerCheckCrc32(payLoadBytes) return err }
analysisMetaEndFrameJSON is reading the MetaEndFrameJSONType data of selectObject response body
analysisMetaEndFrameJSON
go
aliyun/aliyun-oss-go-sdk
oss/select_object_type.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/select_object_type.go
MIT
func (sr *SelectObjectResponse) emptyFrame() { crcCalc := crc32.NewIEEE() sr.WriterForCheckCrc32 = crcCalc sr.Finish = false sr.Frame.ConsumedBytesLength = 0 sr.Frame.OpenLine = false sr.Frame.Version = byte(0) sr.Frame.FrameType = 0 sr.Frame.PayloadLength = 0 sr.Frame.HeaderCheckSum = 0 sr.Frame.Offset = 0 sr.Frame.Data = "" sr.Frame.EndFrame.TotalScanned = 0 sr.Frame.EndFrame.HTTPStatusCode = 0 sr.Frame.EndFrame.ErrorMsg = "" sr.Frame.MetaEndFrameCSV.TotalScanned = 0 sr.Frame.MetaEndFrameCSV.Status = 0 sr.Frame.MetaEndFrameCSV.SplitsCount = 0 sr.Frame.MetaEndFrameCSV.RowsCount = 0 sr.Frame.MetaEndFrameCSV.ColumnsCount = 0 sr.Frame.MetaEndFrameCSV.ErrorMsg = "" sr.Frame.MetaEndFrameJSON.TotalScanned = 0 sr.Frame.MetaEndFrameJSON.Status = 0 sr.Frame.MetaEndFrameJSON.SplitsCount = 0 sr.Frame.MetaEndFrameJSON.RowsCount = 0 sr.Frame.MetaEndFrameJSON.ErrorMsg = "" sr.Frame.PayloadChecksum = 0 }
emptyFrame is emptying SelectObjectResponse Frame information
emptyFrame
go
aliyun/aliyun-oss-go-sdk
oss/select_object_type.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/select_object_type.go
MIT
func bytesToInt(b []byte, ret interface{}) { binBuf := bytes.NewBuffer(b) binary.Read(binBuf, binary.BigEndian, ret) }
bytesToInt byte's array trans to int
bytesToInt
go
aliyun/aliyun-oss-go-sdk
oss/select_object_type.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/select_object_type.go
MIT
func (s *OssBucketMultipartSuite) SetUpSuite(c *C) { bucketName := bucketNamePrefix + RandLowStr(6) if cloudboxControlEndpoint == "" { client, err := New(endpoint, accessID, accessKey) c.Assert(err, IsNil) s.client = client s.client.CreateBucket(bucketName) bucket, err := s.client.Bucket(bucketName) c.Assert(err, IsNil) s.bucket = bucket } else { client, err := New(cloudboxEndpoint, accessID, accessKey) c.Assert(err, IsNil) s.client = client controlClient, err := New(cloudboxControlEndpoint, accessID, accessKey) c.Assert(err, IsNil) s.cloudBoxControlClient = controlClient controlClient.CreateBucket(bucketName) bucket, err := s.client.Bucket(bucketName) c.Assert(err, IsNil) s.bucket = bucket } // Delete part keyMarker := KeyMarker("") uploadIDMarker := UploadIDMarker("") for { lmur, err := s.bucket.ListMultipartUploads(keyMarker, uploadIDMarker) c.Assert(err, IsNil) for _, upload := range lmur.Uploads { var imur = InitiateMultipartUploadResult{Bucket: s.bucket.BucketName, Key: upload.Key, UploadID: upload.UploadID} err = s.bucket.AbortMultipartUpload(imur) c.Assert(err, IsNil) } keyMarker = KeyMarker(lmur.NextKeyMarker) uploadIDMarker = UploadIDMarker(lmur.NextUploadIDMarker) if !lmur.IsTruncated { break } } // Delete objects marker := Marker("") for { lor, err := s.bucket.ListObjects(marker) c.Assert(err, IsNil) for _, object := range lor.Objects { err = s.bucket.DeleteObject(object.Key) c.Assert(err, IsNil) } marker = Marker(lor.NextMarker) if !lor.IsTruncated { break } } testLogger.Println("test multipart started") }
SetUpSuite runs once when the suite starts running
SetUpSuite
go
aliyun/aliyun-oss-go-sdk
oss/multipart_test.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/multipart_test.go
MIT
func (s *OssBucketMultipartSuite) TearDownSuite(c *C) { // Delete part keyMarker := KeyMarker("") uploadIDMarker := UploadIDMarker("") for { lmur, err := s.bucket.ListMultipartUploads(keyMarker, uploadIDMarker) c.Assert(err, IsNil) for _, upload := range lmur.Uploads { var imur = InitiateMultipartUploadResult{Bucket: s.bucket.BucketName, Key: upload.Key, UploadID: upload.UploadID} err = s.bucket.AbortMultipartUpload(imur) c.Assert(err, IsNil) } keyMarker = KeyMarker(lmur.NextKeyMarker) uploadIDMarker = UploadIDMarker(lmur.NextUploadIDMarker) if !lmur.IsTruncated { break } } // Delete objects marker := Marker("") for { lor, err := s.bucket.ListObjects(marker) c.Assert(err, IsNil) for _, object := range lor.Objects { err = s.bucket.DeleteObject(object.Key) c.Assert(err, IsNil) } marker = Marker(lor.NextMarker) if !lor.IsTruncated { break } } // Delete bucket if s.cloudBoxControlClient != nil { err := s.cloudBoxControlClient.DeleteBucket(s.bucket.BucketName) c.Assert(err, IsNil) } else { err := s.client.DeleteBucket(s.bucket.BucketName) c.Assert(err, IsNil) } testLogger.Println("test multipart completed") }
TearDownSuite runs before each test or benchmark starts running
TearDownSuite
go
aliyun/aliyun-oss-go-sdk
oss/multipart_test.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/multipart_test.go
MIT
func (s *OssBucketMultipartSuite) SetUpTest(c *C) { err := removeTempFiles("../oss", ".jpg") c.Assert(err, IsNil) }
SetUpTest runs after each test or benchmark runs
SetUpTest
go
aliyun/aliyun-oss-go-sdk
oss/multipart_test.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/multipart_test.go
MIT
func (s *OssBucketMultipartSuite) TearDownTest(c *C) { err := removeTempFiles("../oss", ".jpg") c.Assert(err, IsNil) err = removeTempFiles("../oss", ".temp") c.Assert(err, IsNil) err = removeTempFiles("../oss", ".txt1") c.Assert(err, IsNil) err = removeTempFiles("../oss", ".txt2") c.Assert(err, IsNil) }
TearDownTest runs once after all tests or benchmarks have finished running
TearDownTest
go
aliyun/aliyun-oss-go-sdk
oss/multipart_test.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/multipart_test.go
MIT
func NewCRC(tab *crc64.Table, init uint64) hash.Hash64 { return &digest{init, tab} }
NewCRC creates a new hash.Hash64 computing the CRC64 checksum using the polynomial represented by the Table.
NewCRC
go
aliyun/aliyun-oss-go-sdk
oss/crc.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crc.go
MIT
func (d *digest) Size() int { return crc64.Size }
Size returns the number of bytes sum will return.
Size
go
aliyun/aliyun-oss-go-sdk
oss/crc.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crc.go
MIT
func (d *digest) BlockSize() int { return 1 }
BlockSize returns the hash's underlying block size. The Write method must be able to accept any amount of data, but it may operate more efficiently if all writes are a multiple of the block size.
BlockSize
go
aliyun/aliyun-oss-go-sdk
oss/crc.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crc.go
MIT
func (d *digest) Reset() { d.crc = 0 }
Reset resets the hash to its initial state.
Reset
go
aliyun/aliyun-oss-go-sdk
oss/crc.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crc.go
MIT
func (d *digest) Write(p []byte) (n int, err error) { d.crc = crc64.Update(d.crc, d.tab, p) return len(p), nil }
Write (via the embedded io.Writer interface) adds more data to the running hash. It never returns an error.
Write
go
aliyun/aliyun-oss-go-sdk
oss/crc.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crc.go
MIT
func (d *digest) Sum64() uint64 { return d.crc }
Sum64 returns CRC64 value.
Sum64
go
aliyun/aliyun-oss-go-sdk
oss/crc.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crc.go
MIT
func (d *digest) Sum(in []byte) []byte { s := d.Sum64() return append(in, byte(s>>56), byte(s>>48), byte(s>>40), byte(s>>32), byte(s>>24), byte(s>>16), byte(s>>8), byte(s)) }
Sum returns hash value.
Sum
go
aliyun/aliyun-oss-go-sdk
oss/crc.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crc.go
MIT
func CRC64Combine(crc1 uint64, crc2 uint64, len2 uint64) uint64 { var even [gf2Dim]uint64 // Even-power-of-two zeros operator var odd [gf2Dim]uint64 // Odd-power-of-two zeros operator // Degenerate case if len2 == 0 { return crc1 } // Put operator for one zero bit in odd odd[0] = crc64.ECMA // CRC64 polynomial var row uint64 = 1 for n := 1; n < gf2Dim; n++ { odd[n] = row row <<= 1 } // Put operator for two zero bits in even gf2MatrixSquare(even[:], odd[:]) // Put operator for four zero bits in odd gf2MatrixSquare(odd[:], even[:]) // Apply len2 zeros to crc1, first square will put the operator for one zero byte, eight zero bits, in even for { // Apply zeros operator for this bit of len2 gf2MatrixSquare(even[:], odd[:]) if len2&1 != 0 { crc1 = gf2MatrixTimes(even[:], crc1) } len2 >>= 1 // If no more bits set, then done if len2 == 0 { break } // Another iteration of the loop with odd and even swapped gf2MatrixSquare(odd[:], even[:]) if len2&1 != 0 { crc1 = gf2MatrixTimes(odd[:], crc1) } len2 >>= 1 // If no more bits set, then done if len2 == 0 { break } } // Return combined CRC crc1 ^= crc2 return crc1 }
CRC64Combine combines CRC64
CRC64Combine
go
aliyun/aliyun-oss-go-sdk
oss/crc.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/crc.go
MIT
func (s *OssUploadSuite) SetUpSuite(c *C) { bucketName := bucketNamePrefix + RandLowStr(6) if cloudboxControlEndpoint == "" { client, err := New(endpoint, accessID, accessKey) c.Assert(err, IsNil) s.client = client s.client.CreateBucket(bucketName) bucket, err := s.client.Bucket(bucketName) c.Assert(err, IsNil) s.bucket = bucket } else { client, err := New(cloudboxEndpoint, accessID, accessKey) c.Assert(err, IsNil) s.client = client controlClient, err := New(cloudboxControlEndpoint, accessID, accessKey) c.Assert(err, IsNil) s.cloudBoxControlClient = controlClient controlClient.CreateBucket(bucketName) bucket, err := s.client.Bucket(bucketName) c.Assert(err, IsNil) s.bucket = bucket } testLogger.Println("test upload started") }
SetUpSuite runs once when the suite starts running
SetUpSuite
go
aliyun/aliyun-oss-go-sdk
oss/upload_test.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/upload_test.go
MIT
func (s *OssUploadSuite) TearDownSuite(c *C) { // Delete part keyMarker := KeyMarker("") uploadIDMarker := UploadIDMarker("") for { lmur, err := s.bucket.ListMultipartUploads(keyMarker, uploadIDMarker) c.Assert(err, IsNil) for _, upload := range lmur.Uploads { var imur = InitiateMultipartUploadResult{Bucket: s.bucket.BucketName, Key: upload.Key, UploadID: upload.UploadID} err = s.bucket.AbortMultipartUpload(imur) c.Assert(err, IsNil) } keyMarker = KeyMarker(lmur.NextKeyMarker) uploadIDMarker = UploadIDMarker(lmur.NextUploadIDMarker) if !lmur.IsTruncated { break } } // Delete objects marker := Marker("") for { lor, err := s.bucket.ListObjects(marker) c.Assert(err, IsNil) for _, object := range lor.Objects { err = s.bucket.DeleteObject(object.Key) c.Assert(err, IsNil) } marker = Marker(lor.NextMarker) if !lor.IsTruncated { break } } // Delete bucket if s.cloudBoxControlClient != nil { err := s.cloudBoxControlClient.DeleteBucket(s.bucket.BucketName) c.Assert(err, IsNil) } else { err := s.client.DeleteBucket(s.bucket.BucketName) c.Assert(err, IsNil) } testLogger.Println("test upload completed") }
TearDownSuite runs before each test or benchmark starts running
TearDownSuite
go
aliyun/aliyun-oss-go-sdk
oss/upload_test.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/upload_test.go
MIT
func (s *OssUploadSuite) SetUpTest(c *C) { err := removeTempFiles("../oss", ".jpg") c.Assert(err, IsNil) }
SetUpTest runs after each test or benchmark runs
SetUpTest
go
aliyun/aliyun-oss-go-sdk
oss/upload_test.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/upload_test.go
MIT
func (s *OssUploadSuite) TearDownTest(c *C) { err := removeTempFiles("../oss", ".jpg") c.Assert(err, IsNil) }
TearDownTest runs once after all tests or benchmarks have finished running
TearDownTest
go
aliyun/aliyun-oss-go-sdk
oss/upload_test.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/upload_test.go
MIT
func ErrorHooker(id int, chunk FileChunk) error { if chunk.Number == 5 { time.Sleep(time.Second) return fmt.Errorf("ErrorHooker") } return nil }
ErrorHooker is a UploadPart hook---it will fail the 5th part's upload.
ErrorHooker
go
aliyun/aliyun-oss-go-sdk
oss/upload_test.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/upload_test.go
MIT
func (listener *OssSelectProgressListener) ProgressChanged(event *ProgressEvent) { switch event.EventType { case TransferStartedEvent: testLogger.Printf("Transfer Started.\n") case TransferDataEvent: testLogger.Printf("Transfer Data, This time consumedBytes: %d \n", event.ConsumedBytes) case TransferCompletedEvent: testLogger.Printf("Transfer Completed, This time consumedBytes: %d.\n", event.ConsumedBytes) case TransferFailedEvent: testLogger.Printf("Transfer Failed, This time consumedBytes: %d.\n", event.ConsumedBytes) default: } }
ProgressChanged handles progress event
ProgressChanged
go
aliyun/aliyun-oss-go-sdk
oss/select_csv_objcet_test.go
https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/oss/select_csv_objcet_test.go
MIT