20 var sys_release string
21 var sys_machine string
24 sys_name = runtime.GOOS
26 sys_machine = runtime.GOARCH
28 if out, err := exec.Command("uname", "-s").CombinedOutput(); err == nil {
29 sys_name = string(bytes.TrimSpace(out))
31 if out, err := exec.Command("uname", "-r").CombinedOutput(); err == nil {
32 sys_release = string(bytes.TrimSpace(out))
34 if out, err := exec.Command("uname", "-m").CombinedOutput(); err == nil {
35 sys_machine = string(bytes.TrimSpace(out))
39 // userAgent gets user agent
40 // It has the SDK version information, OS information and GO version
41 func userAgent() string {
43 return fmt.Sprintf("aliyun-sdk-go/%s (%s/%s/%s;%s)", Version, sys.name,
44 sys.release, sys.machine, runtime.Version())
48 name string // OS name such as windows/Linux
49 release string // OS version 2.6.32-220.23.2.ali1089.el5.x86_64 etc
50 machine string // CPU type amd64/x86_64
53 // getSysInfo gets system info
54 // gets the OS information and CPU type
55 func getSysInfo() sysInfo {
56 return sysInfo{name: sys_name, release: sys_release, machine: sys_machine}
59 // GetRangeConfig gets the download range from the options.
60 func GetRangeConfig(options []Option) (*UnpackedRange, error) {
61 rangeOpt, err := FindOption(options, HTTPHeaderRange, nil)
62 if err != nil || rangeOpt == nil {
65 return ParseRange(rangeOpt.(string))
69 type UnpackedRange struct {
70 HasStart bool // Flag indicates if the start point is specified
71 HasEnd bool // Flag indicates if the end point is specified
72 Start int64 // Start point
73 End int64 // End point
76 // InvalidRangeError returns invalid range error
77 func InvalidRangeError(r string) error {
78 return fmt.Errorf("InvalidRange %s", r)
81 func GetRangeString(unpackRange UnpackedRange) string {
83 if unpackRange.HasStart && unpackRange.HasEnd {
84 strRange = fmt.Sprintf("%d-%d", unpackRange.Start, unpackRange.End)
85 } else if unpackRange.HasStart {
86 strRange = fmt.Sprintf("%d-", unpackRange.Start)
87 } else if unpackRange.HasEnd {
88 strRange = fmt.Sprintf("-%d", unpackRange.End)
93 // ParseRange parse various styles of range such as bytes=M-N
94 func ParseRange(normalizedRange string) (*UnpackedRange, error) {
101 // Bytes==M-N or ranges=M-N
102 nrSlice := strings.Split(normalizedRange, "=")
103 if len(nrSlice) != 2 || nrSlice[0] != "bytes" {
104 return nil, InvalidRangeError(normalizedRange)
108 rSlice := strings.Split(nrSlice[1], ",")
111 if strings.HasSuffix(rStr, "-") { // M-
112 startStr := rStr[:len(rStr)-1]
113 start, err = strconv.ParseInt(startStr, 10, 64)
115 return nil, InvalidRangeError(normalizedRange)
118 } else if strings.HasPrefix(rStr, "-") { // -N
120 end, err = strconv.ParseInt(len, 10, 64)
122 return nil, InvalidRangeError(normalizedRange)
125 return nil, InvalidRangeError(normalizedRange)
129 valSlice := strings.Split(rStr, "-")
130 if len(valSlice) != 2 {
131 return nil, InvalidRangeError(normalizedRange)
133 start, err = strconv.ParseInt(valSlice[0], 10, 64)
135 return nil, InvalidRangeError(normalizedRange)
138 end, err = strconv.ParseInt(valSlice[1], 10, 64)
140 return nil, InvalidRangeError(normalizedRange)
145 return &UnpackedRange{hasStart, hasEnd, start, end}, nil
148 // AdjustRange returns adjusted range, adjust the range according to the length of the file
149 func AdjustRange(ur *UnpackedRange, size int64) (start, end int64) {
154 if ur.HasStart && ur.HasEnd {
157 if ur.Start < 0 || ur.Start >= size || ur.End > size || ur.Start > ur.End {
161 } else if ur.HasStart {
164 if ur.Start < 0 || ur.Start >= size {
167 } else if ur.HasEnd {
168 start = size - ur.End
170 if ur.End < 0 || ur.End > size {
178 // GetNowSec returns Unix time, the number of seconds elapsed since January 1, 1970 UTC.
179 // gets the current time in Unix time, in seconds.
180 func GetNowSec() int64 {
181 return time.Now().Unix()
184 // GetNowNanoSec returns t as a Unix time, the number of nanoseconds elapsed
185 // since January 1, 1970 UTC. The result is undefined if the Unix time
186 // in nanoseconds cannot be represented by an int64. Note that this
187 // means the result of calling UnixNano on the zero Time is undefined.
188 // gets the current time in Unix time, in nanoseconds.
189 func GetNowNanoSec() int64 {
190 return time.Now().UnixNano()
193 // GetNowGMT gets the current time in GMT format.
194 func GetNowGMT() string {
195 return time.Now().UTC().Format(http.TimeFormat)
198 // FileChunk is the file chunk definition
199 type FileChunk struct {
200 Number int // Chunk number
201 Offset int64 // Chunk offset
202 Size int64 // Chunk size.
205 // SplitFileByPartNum splits big file into parts by the num of parts.
206 // Split the file with specified parts count, returns the split result when error is nil.
207 func SplitFileByPartNum(fileName string, chunkNum int) ([]FileChunk, error) {
208 if chunkNum <= 0 || chunkNum > 10000 {
209 return nil, errors.New("chunkNum invalid")
212 file, err := os.Open(fileName)
218 stat, err := file.Stat()
223 if int64(chunkNum) > stat.Size() {
224 return nil, errors.New("oss: chunkNum invalid")
227 var chunks []FileChunk
228 var chunk = FileChunk{}
229 var chunkN = (int64)(chunkNum)
230 for i := int64(0); i < chunkN; i++ {
231 chunk.Number = int(i + 1)
232 chunk.Offset = i * (stat.Size() / chunkN)
234 chunk.Size = stat.Size()/chunkN + stat.Size()%chunkN
236 chunk.Size = stat.Size() / chunkN
238 chunks = append(chunks, chunk)
244 // SplitFileByPartSize splits big file into parts by the size of parts.
245 // Splits the file by the part size. Returns the FileChunk when error is nil.
246 func SplitFileByPartSize(fileName string, chunkSize int64) ([]FileChunk, error) {
248 return nil, errors.New("chunkSize invalid")
251 file, err := os.Open(fileName)
257 stat, err := file.Stat()
261 var chunkN = stat.Size() / chunkSize
263 return nil, errors.New("Too many parts, please increase part size")
266 var chunks []FileChunk
267 var chunk = FileChunk{}
268 for i := int64(0); i < chunkN; i++ {
269 chunk.Number = int(i + 1)
270 chunk.Offset = i * chunkSize
271 chunk.Size = chunkSize
272 chunks = append(chunks, chunk)
275 if stat.Size()%chunkSize > 0 {
276 chunk.Number = len(chunks) + 1
277 chunk.Offset = int64(len(chunks)) * chunkSize
278 chunk.Size = stat.Size() % chunkSize
279 chunks = append(chunks, chunk)
285 // GetPartEnd calculates the end position
286 func GetPartEnd(begin int64, total int64, per int64) int64 {
287 if begin+per > total {
290 return begin + per - 1
293 // CrcTable returns the table constructed from the specified polynomial
294 var CrcTable = func() *crc64.Table {
295 return crc64.MakeTable(crc64.ECMA)
298 // CrcTable returns the table constructed from the specified polynomial
299 var crc32Table = func() *crc32.Table {
300 return crc32.MakeTable(crc32.IEEE)
303 // choiceTransferPartOption choices valid option supported by Uploadpart or DownloadPart
304 func ChoiceTransferPartOption(options []Option) []Option {
305 var outOption []Option
307 listener, _ := FindOption(options, progressListener, nil)
309 outOption = append(outOption, Progress(listener.(ProgressListener)))
312 payer, _ := FindOption(options, HTTPHeaderOssRequester, nil)
314 outOption = append(outOption, RequestPayer(PayerType(payer.(string))))
317 versionId, _ := FindOption(options, "versionId", nil)
318 if versionId != nil {
319 outOption = append(outOption, VersionId(versionId.(string)))
322 trafficLimit, _ := FindOption(options, HTTPHeaderOssTrafficLimit, nil)
323 if trafficLimit != nil {
324 speed, _ := strconv.ParseInt(trafficLimit.(string), 10, 64)
325 outOption = append(outOption, TrafficLimitHeader(speed))
328 respHeader, _ := FindOption(options, responseHeader, nil)
329 if respHeader != nil {
330 outOption = append(outOption, GetResponseHeader(respHeader.(*http.Header)))
336 // ChoiceCompletePartOption choices valid option supported by CompleteMulitiPart
337 func ChoiceCompletePartOption(options []Option) []Option {
338 var outOption []Option
340 listener, _ := FindOption(options, progressListener, nil)
342 outOption = append(outOption, Progress(listener.(ProgressListener)))
345 payer, _ := FindOption(options, HTTPHeaderOssRequester, nil)
347 outOption = append(outOption, RequestPayer(PayerType(payer.(string))))
350 acl, _ := FindOption(options, HTTPHeaderOssObjectACL, nil)
352 outOption = append(outOption, ObjectACL(ACLType(acl.(string))))
355 callback, _ := FindOption(options, HTTPHeaderOssCallback, nil)
357 outOption = append(outOption, Callback(callback.(string)))
360 callbackVar, _ := FindOption(options, HTTPHeaderOssCallbackVar, nil)
361 if callbackVar != nil {
362 outOption = append(outOption, CallbackVar(callbackVar.(string)))
365 respHeader, _ := FindOption(options, responseHeader, nil)
366 if respHeader != nil {
367 outOption = append(outOption, GetResponseHeader(respHeader.(*http.Header)))
370 forbidOverWrite, _ := FindOption(options, HTTPHeaderOssForbidOverWrite, nil)
371 if forbidOverWrite != nil {
372 if forbidOverWrite.(string) == "true" {
373 outOption = append(outOption, ForbidOverWrite(true))
375 outOption = append(outOption, ForbidOverWrite(false))
382 // ChoiceAbortPartOption choices valid option supported by AbortMultipartUpload
383 func ChoiceAbortPartOption(options []Option) []Option {
384 var outOption []Option
385 payer, _ := FindOption(options, HTTPHeaderOssRequester, nil)
387 outOption = append(outOption, RequestPayer(PayerType(payer.(string))))
390 respHeader, _ := FindOption(options, responseHeader, nil)
391 if respHeader != nil {
392 outOption = append(outOption, GetResponseHeader(respHeader.(*http.Header)))
398 // ChoiceHeadObjectOption choices valid option supported by HeadObject
399 func ChoiceHeadObjectOption(options []Option) []Option {
400 var outOption []Option
402 // not select HTTPHeaderRange to get whole object length
403 payer, _ := FindOption(options, HTTPHeaderOssRequester, nil)
405 outOption = append(outOption, RequestPayer(PayerType(payer.(string))))
408 versionId, _ := FindOption(options, "versionId", nil)
409 if versionId != nil {
410 outOption = append(outOption, VersionId(versionId.(string)))
413 respHeader, _ := FindOption(options, responseHeader, nil)
414 if respHeader != nil {
415 outOption = append(outOption, GetResponseHeader(respHeader.(*http.Header)))
421 func CheckBucketName(bucketName string) error {
422 nameLen := len(bucketName)
423 if nameLen < 3 || nameLen > 63 {
424 return fmt.Errorf("bucket name %s len is between [3-63],now is %d", bucketName, nameLen)
427 for _, v := range bucketName {
428 if !(('a' <= v && v <= 'z') || ('0' <= v && v <= '9') || v == '-') {
429 return fmt.Errorf("bucket name %s can only include lowercase letters, numbers, and -", bucketName)
432 if bucketName[0] == '-' || bucketName[nameLen-1] == '-' {
433 return fmt.Errorf("bucket name %s must start and end with a lowercase letter or number", bucketName)
438 func GetReaderLen(reader io.Reader) (int64, error) {
439 var contentLength int64
441 switch v := reader.(type) {
443 contentLength = int64(v.Len())
445 contentLength = int64(v.Len())
446 case *strings.Reader:
447 contentLength = int64(v.Len())
449 fInfo, fError := v.Stat()
451 err = fmt.Errorf("can't get reader content length,%s", fError.Error())
453 contentLength = fInfo.Size()
455 case *io.LimitedReader:
456 contentLength = int64(v.N)
457 case *LimitedReadCloser:
458 contentLength = int64(v.N)
460 err = fmt.Errorf("can't get reader content length,unkown reader type")
462 return contentLength, err
465 func LimitReadCloser(r io.Reader, n int64) io.Reader {
466 var lc LimitedReadCloser
472 // LimitedRC support Close()
473 type LimitedReadCloser struct {
477 func (lc *LimitedReadCloser) Close() error {
478 if closer, ok := lc.R.(io.ReadCloser); ok {
479 return closer.Close()
484 type DiscardReadCloser struct {
489 func (drc *DiscardReadCloser) Read(b []byte) (int, error) {
490 n, err := drc.RC.Read(b)
491 if drc.Discard == 0 || n <= 0 {
495 if n <= drc.Discard {
500 realLen := n - drc.Discard
501 copy(b[0:realLen], b[drc.Discard:n])
506 func (drc *DiscardReadCloser) Close() error {
507 closer, ok := drc.RC.(io.ReadCloser)
509 return closer.Close()