option.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. package oss
  2. import (
  3. "fmt"
  4. "net/http"
  5. "net/url"
  6. "strconv"
  7. "strings"
  8. "time"
  9. )
  10. type optionType string
  11. const (
  12. optionParam optionType = "HTTPParameter" // URL parameter
  13. optionHTTP optionType = "HTTPHeader" // HTTP header
  14. optionArg optionType = "FuncArgument" // Function argument
  15. )
  16. const (
  17. deleteObjectsQuiet = "delete-objects-quiet"
  18. routineNum = "x-routine-num"
  19. checkpointConfig = "x-cp-config"
  20. initCRC64 = "init-crc64"
  21. progressListener = "x-progress-listener"
  22. storageClass = "storage-class"
  23. responseHeader = "x-response-header"
  24. redundancyType = "redundancy-type"
  25. )
  26. type (
  27. optionValue struct {
  28. Value interface{}
  29. Type optionType
  30. }
  31. // Option HTTP option
  32. Option func(map[string]optionValue) error
  33. )
  34. // ACL is an option to set X-Oss-Acl header
  35. func ACL(acl ACLType) Option {
  36. return setHeader(HTTPHeaderOssACL, string(acl))
  37. }
  38. // ContentType is an option to set Content-Type header
  39. func ContentType(value string) Option {
  40. return setHeader(HTTPHeaderContentType, value)
  41. }
  42. // ContentLength is an option to set Content-Length header
  43. func ContentLength(length int64) Option {
  44. return setHeader(HTTPHeaderContentLength, strconv.FormatInt(length, 10))
  45. }
  46. // CacheControl is an option to set Cache-Control header
  47. func CacheControl(value string) Option {
  48. return setHeader(HTTPHeaderCacheControl, value)
  49. }
  50. // ContentDisposition is an option to set Content-Disposition header
  51. func ContentDisposition(value string) Option {
  52. return setHeader(HTTPHeaderContentDisposition, value)
  53. }
  54. // ContentEncoding is an option to set Content-Encoding header
  55. func ContentEncoding(value string) Option {
  56. return setHeader(HTTPHeaderContentEncoding, value)
  57. }
  58. // ContentLanguage is an option to set Content-Language header
  59. func ContentLanguage(value string) Option {
  60. return setHeader(HTTPHeaderContentLanguage, value)
  61. }
  62. // ContentMD5 is an option to set Content-MD5 header
  63. func ContentMD5(value string) Option {
  64. return setHeader(HTTPHeaderContentMD5, value)
  65. }
  66. // Expires is an option to set Expires header
  67. func Expires(t time.Time) Option {
  68. return setHeader(HTTPHeaderExpires, t.Format(http.TimeFormat))
  69. }
  70. // Meta is an option to set Meta header
  71. func Meta(key, value string) Option {
  72. return setHeader(HTTPHeaderOssMetaPrefix+key, value)
  73. }
  74. // Range is an option to set Range header, [start, end]
  75. func Range(start, end int64) Option {
  76. return setHeader(HTTPHeaderRange, fmt.Sprintf("bytes=%d-%d", start, end))
  77. }
  78. // NormalizedRange is an option to set Range header, such as 1024-2048 or 1024- or -2048
  79. func NormalizedRange(nr string) Option {
  80. return setHeader(HTTPHeaderRange, fmt.Sprintf("bytes=%s", strings.TrimSpace(nr)))
  81. }
  82. // AcceptEncoding is an option to set Accept-Encoding header
  83. func AcceptEncoding(value string) Option {
  84. return setHeader(HTTPHeaderAcceptEncoding, value)
  85. }
  86. // IfModifiedSince is an option to set If-Modified-Since header
  87. func IfModifiedSince(t time.Time) Option {
  88. return setHeader(HTTPHeaderIfModifiedSince, t.Format(http.TimeFormat))
  89. }
  90. // IfUnmodifiedSince is an option to set If-Unmodified-Since header
  91. func IfUnmodifiedSince(t time.Time) Option {
  92. return setHeader(HTTPHeaderIfUnmodifiedSince, t.Format(http.TimeFormat))
  93. }
  94. // IfMatch is an option to set If-Match header
  95. func IfMatch(value string) Option {
  96. return setHeader(HTTPHeaderIfMatch, value)
  97. }
  98. // IfNoneMatch is an option to set IfNoneMatch header
  99. func IfNoneMatch(value string) Option {
  100. return setHeader(HTTPHeaderIfNoneMatch, value)
  101. }
  102. // CopySource is an option to set X-Oss-Copy-Source header
  103. func CopySource(sourceBucket, sourceObject string) Option {
  104. return setHeader(HTTPHeaderOssCopySource, "/"+sourceBucket+"/"+sourceObject)
  105. }
  106. // CopySourceVersion is an option to set X-Oss-Copy-Source header,include versionId
  107. func CopySourceVersion(sourceBucket, sourceObject string, versionId string) Option {
  108. return setHeader(HTTPHeaderOssCopySource, "/"+sourceBucket+"/"+sourceObject+"?"+"versionId="+versionId)
  109. }
  110. // CopySourceRange is an option to set X-Oss-Copy-Source header
  111. func CopySourceRange(startPosition, partSize int64) Option {
  112. val := "bytes=" + strconv.FormatInt(startPosition, 10) + "-" +
  113. strconv.FormatInt((startPosition+partSize-1), 10)
  114. return setHeader(HTTPHeaderOssCopySourceRange, val)
  115. }
  116. // CopySourceIfMatch is an option to set X-Oss-Copy-Source-If-Match header
  117. func CopySourceIfMatch(value string) Option {
  118. return setHeader(HTTPHeaderOssCopySourceIfMatch, value)
  119. }
  120. // CopySourceIfNoneMatch is an option to set X-Oss-Copy-Source-If-None-Match header
  121. func CopySourceIfNoneMatch(value string) Option {
  122. return setHeader(HTTPHeaderOssCopySourceIfNoneMatch, value)
  123. }
  124. // CopySourceIfModifiedSince is an option to set X-Oss-CopySource-If-Modified-Since header
  125. func CopySourceIfModifiedSince(t time.Time) Option {
  126. return setHeader(HTTPHeaderOssCopySourceIfModifiedSince, t.Format(http.TimeFormat))
  127. }
  128. // CopySourceIfUnmodifiedSince is an option to set X-Oss-Copy-Source-If-Unmodified-Since header
  129. func CopySourceIfUnmodifiedSince(t time.Time) Option {
  130. return setHeader(HTTPHeaderOssCopySourceIfUnmodifiedSince, t.Format(http.TimeFormat))
  131. }
  132. // MetadataDirective is an option to set X-Oss-Metadata-Directive header
  133. func MetadataDirective(directive MetadataDirectiveType) Option {
  134. return setHeader(HTTPHeaderOssMetadataDirective, string(directive))
  135. }
  136. // ServerSideEncryption is an option to set X-Oss-Server-Side-Encryption header
  137. func ServerSideEncryption(value string) Option {
  138. return setHeader(HTTPHeaderOssServerSideEncryption, value)
  139. }
  140. // ServerSideEncryptionKeyID is an option to set X-Oss-Server-Side-Encryption-Key-Id header
  141. func ServerSideEncryptionKeyID(value string) Option {
  142. return setHeader(HTTPHeaderOssServerSideEncryptionKeyID, value)
  143. }
  144. // ObjectACL is an option to set X-Oss-Object-Acl header
  145. func ObjectACL(acl ACLType) Option {
  146. return setHeader(HTTPHeaderOssObjectACL, string(acl))
  147. }
  148. // symlinkTarget is an option to set X-Oss-Symlink-Target
  149. func symlinkTarget(targetObjectKey string) Option {
  150. return setHeader(HTTPHeaderOssSymlinkTarget, targetObjectKey)
  151. }
  152. // Origin is an option to set Origin header
  153. func Origin(value string) Option {
  154. return setHeader(HTTPHeaderOrigin, value)
  155. }
  156. // ObjectStorageClass is an option to set the storage class of object
  157. func ObjectStorageClass(storageClass StorageClassType) Option {
  158. return setHeader(HTTPHeaderOssStorageClass, string(storageClass))
  159. }
  160. // Callback is an option to set callback values
  161. func Callback(callback string) Option {
  162. return setHeader(HTTPHeaderOssCallback, callback)
  163. }
  164. // CallbackVar is an option to set callback user defined values
  165. func CallbackVar(callbackVar string) Option {
  166. return setHeader(HTTPHeaderOssCallbackVar, callbackVar)
  167. }
  168. // RequestPayer is an option to set payer who pay for the request
  169. func RequestPayer(payerType PayerType) Option {
  170. return setHeader(HTTPHeaderOssRequester, strings.ToLower(string(payerType)))
  171. }
  172. // RequestPayerParam is an option to set payer who pay for the request
  173. func RequestPayerParam(payerType PayerType) Option {
  174. return addParam(strings.ToLower(HTTPHeaderOssRequester), strings.ToLower(string(payerType)))
  175. }
  176. // SetTagging is an option to set object tagging
  177. func SetTagging(tagging Tagging) Option {
  178. if len(tagging.Tags) == 0 {
  179. return nil
  180. }
  181. taggingValue := ""
  182. for index, tag := range tagging.Tags {
  183. if index != 0 {
  184. taggingValue += "&"
  185. }
  186. taggingValue += url.QueryEscape(tag.Key) + "=" + url.QueryEscape(tag.Value)
  187. }
  188. return setHeader(HTTPHeaderOssTagging, taggingValue)
  189. }
  190. // TaggingDirective is an option to set X-Oss-Metadata-Directive header
  191. func TaggingDirective(directive TaggingDirectiveType) Option {
  192. return setHeader(HTTPHeaderOssTaggingDirective, string(directive))
  193. }
  194. // ACReqMethod is an option to set Access-Control-Request-Method header
  195. func ACReqMethod(value string) Option {
  196. return setHeader(HTTPHeaderACReqMethod, value)
  197. }
  198. // ACReqHeaders is an option to set Access-Control-Request-Headers header
  199. func ACReqHeaders(value string) Option {
  200. return setHeader(HTTPHeaderACReqHeaders, value)
  201. }
  202. // TrafficLimitHeader is an option to set X-Oss-Traffic-Limit
  203. func TrafficLimitHeader(value int64) Option {
  204. return setHeader(HTTPHeaderOssTrafficLimit, strconv.FormatInt(value, 10))
  205. }
  206. // ForbidOverWrite is an option to set X-Oss-Forbid-Overwrite
  207. func ForbidOverWrite(forbidWrite bool) Option {
  208. if forbidWrite {
  209. return setHeader(HTTPHeaderOssForbidOverWrite, "true")
  210. } else {
  211. return setHeader(HTTPHeaderOssForbidOverWrite, "false")
  212. }
  213. }
  214. // Delimiter is an option to set delimiler parameter
  215. func Delimiter(value string) Option {
  216. return addParam("delimiter", value)
  217. }
  218. // Marker is an option to set marker parameter
  219. func Marker(value string) Option {
  220. return addParam("marker", value)
  221. }
  222. // MaxKeys is an option to set maxkeys parameter
  223. func MaxKeys(value int) Option {
  224. return addParam("max-keys", strconv.Itoa(value))
  225. }
  226. // Prefix is an option to set prefix parameter
  227. func Prefix(value string) Option {
  228. return addParam("prefix", value)
  229. }
  230. // EncodingType is an option to set encoding-type parameter
  231. func EncodingType(value string) Option {
  232. return addParam("encoding-type", value)
  233. }
  234. // MaxUploads is an option to set max-uploads parameter
  235. func MaxUploads(value int) Option {
  236. return addParam("max-uploads", strconv.Itoa(value))
  237. }
  238. // KeyMarker is an option to set key-marker parameter
  239. func KeyMarker(value string) Option {
  240. return addParam("key-marker", value)
  241. }
  242. // VersionIdMarker is an option to set version-id-marker parameter
  243. func VersionIdMarker(value string) Option {
  244. return addParam("version-id-marker", value)
  245. }
  246. // VersionId is an option to set versionId parameter
  247. func VersionId(value string) Option {
  248. return addParam("versionId", value)
  249. }
  250. // TagKey is an option to set tag key parameter
  251. func TagKey(value string) Option {
  252. return addParam("tag-key", value)
  253. }
  254. // TagValue is an option to set tag value parameter
  255. func TagValue(value string) Option {
  256. return addParam("tag-value", value)
  257. }
  258. // UploadIDMarker is an option to set upload-id-marker parameter
  259. func UploadIDMarker(value string) Option {
  260. return addParam("upload-id-marker", value)
  261. }
  262. // MaxParts is an option to set max-parts parameter
  263. func MaxParts(value int) Option {
  264. return addParam("max-parts", strconv.Itoa(value))
  265. }
  266. // PartNumberMarker is an option to set part-number-marker parameter
  267. func PartNumberMarker(value int) Option {
  268. return addParam("part-number-marker", strconv.Itoa(value))
  269. }
  270. // Sequential is an option to set sequential parameter for InitiateMultipartUpload
  271. func Sequential() Option {
  272. return addParam("sequential", "")
  273. }
  274. // DeleteObjectsQuiet false:DeleteObjects in verbose mode; true:DeleteObjects in quite mode. Default is false.
  275. func DeleteObjectsQuiet(isQuiet bool) Option {
  276. return addArg(deleteObjectsQuiet, isQuiet)
  277. }
  278. // StorageClass bucket storage class
  279. func StorageClass(value StorageClassType) Option {
  280. return addArg(storageClass, value)
  281. }
  282. // RedundancyType bucket data redundancy type
  283. func RedundancyType(value DataRedundancyType) Option {
  284. return addArg(redundancyType, value)
  285. }
  286. // Checkpoint configuration
  287. type cpConfig struct {
  288. IsEnable bool
  289. FilePath string
  290. DirPath string
  291. }
  292. // Checkpoint sets the isEnable flag and checkpoint file path for DownloadFile/UploadFile.
  293. func Checkpoint(isEnable bool, filePath string) Option {
  294. return addArg(checkpointConfig, &cpConfig{IsEnable: isEnable, FilePath: filePath})
  295. }
  296. // CheckpointDir sets the isEnable flag and checkpoint dir path for DownloadFile/UploadFile.
  297. func CheckpointDir(isEnable bool, dirPath string) Option {
  298. return addArg(checkpointConfig, &cpConfig{IsEnable: isEnable, DirPath: dirPath})
  299. }
  300. // Routines DownloadFile/UploadFile routine count
  301. func Routines(n int) Option {
  302. return addArg(routineNum, n)
  303. }
  304. // InitCRC Init AppendObject CRC
  305. func InitCRC(initCRC uint64) Option {
  306. return addArg(initCRC64, initCRC)
  307. }
  308. // Progress set progress listener
  309. func Progress(listener ProgressListener) Option {
  310. return addArg(progressListener, listener)
  311. }
  312. // GetResponseHeader for get response http header
  313. func GetResponseHeader(respHeader *http.Header) Option {
  314. return addArg(responseHeader, respHeader)
  315. }
  316. // ResponseContentType is an option to set response-content-type param
  317. func ResponseContentType(value string) Option {
  318. return addParam("response-content-type", value)
  319. }
  320. // ResponseContentLanguage is an option to set response-content-language param
  321. func ResponseContentLanguage(value string) Option {
  322. return addParam("response-content-language", value)
  323. }
  324. // ResponseExpires is an option to set response-expires param
  325. func ResponseExpires(value string) Option {
  326. return addParam("response-expires", value)
  327. }
  328. // ResponseCacheControl is an option to set response-cache-control param
  329. func ResponseCacheControl(value string) Option {
  330. return addParam("response-cache-control", value)
  331. }
  332. // ResponseContentDisposition is an option to set response-content-disposition param
  333. func ResponseContentDisposition(value string) Option {
  334. return addParam("response-content-disposition", value)
  335. }
  336. // ResponseContentEncoding is an option to set response-content-encoding param
  337. func ResponseContentEncoding(value string) Option {
  338. return addParam("response-content-encoding", value)
  339. }
  340. // Process is an option to set x-oss-process param
  341. func Process(value string) Option {
  342. return addParam("x-oss-process", value)
  343. }
  344. // TrafficLimitParam is a option to set x-oss-traffic-limit
  345. func TrafficLimitParam(value int64) Option {
  346. return addParam("x-oss-traffic-limit", strconv.FormatInt(value, 10))
  347. }
  348. func setHeader(key string, value interface{}) Option {
  349. return func(params map[string]optionValue) error {
  350. if value == nil {
  351. return nil
  352. }
  353. params[key] = optionValue{value, optionHTTP}
  354. return nil
  355. }
  356. }
  357. func addParam(key string, value interface{}) Option {
  358. return func(params map[string]optionValue) error {
  359. if value == nil {
  360. return nil
  361. }
  362. params[key] = optionValue{value, optionParam}
  363. return nil
  364. }
  365. }
  366. func addArg(key string, value interface{}) Option {
  367. return func(params map[string]optionValue) error {
  368. if value == nil {
  369. return nil
  370. }
  371. params[key] = optionValue{value, optionArg}
  372. return nil
  373. }
  374. }
  375. func handleOptions(headers map[string]string, options []Option) error {
  376. params := map[string]optionValue{}
  377. for _, option := range options {
  378. if option != nil {
  379. if err := option(params); err != nil {
  380. return err
  381. }
  382. }
  383. }
  384. for k, v := range params {
  385. if v.Type == optionHTTP {
  386. headers[k] = v.Value.(string)
  387. }
  388. }
  389. return nil
  390. }
  391. func getRawParams(options []Option) (map[string]interface{}, error) {
  392. // Option
  393. params := map[string]optionValue{}
  394. for _, option := range options {
  395. if option != nil {
  396. if err := option(params); err != nil {
  397. return nil, err
  398. }
  399. }
  400. }
  401. paramsm := map[string]interface{}{}
  402. // Serialize
  403. for k, v := range params {
  404. if v.Type == optionParam {
  405. vs := params[k]
  406. paramsm[k] = vs.Value.(string)
  407. }
  408. }
  409. return paramsm, nil
  410. }
  411. func findOption(options []Option, param string, defaultVal interface{}) (interface{}, error) {
  412. params := map[string]optionValue{}
  413. for _, option := range options {
  414. if option != nil {
  415. if err := option(params); err != nil {
  416. return nil, err
  417. }
  418. }
  419. }
  420. if val, ok := params[param]; ok {
  421. return val.Value, nil
  422. }
  423. return defaultVal, nil
  424. }
  425. func isOptionSet(options []Option, option string) (bool, interface{}, error) {
  426. params := map[string]optionValue{}
  427. for _, option := range options {
  428. if option != nil {
  429. if err := option(params); err != nil {
  430. return false, nil, err
  431. }
  432. }
  433. }
  434. if val, ok := params[option]; ok {
  435. return true, val.Value, nil
  436. }
  437. return false, nil, nil
  438. }
  439. func deleteOption(options []Option, strKey string) []Option {
  440. var outOption []Option
  441. params := map[string]optionValue{}
  442. for _, option := range options {
  443. if option != nil {
  444. option(params)
  445. _, exist := params[strKey]
  446. if !exist {
  447. outOption = append(outOption, option)
  448. } else {
  449. delete(params, strKey)
  450. }
  451. }
  452. }
  453. return outOption
  454. }
  455. func GetRequestId(header http.Header) string {
  456. return header.Get("x-oss-request-id")
  457. }
  458. func GetVersionId(header http.Header) string {
  459. return header.Get("x-oss-version-id")
  460. }
  461. func GetCopySrcVersionId(header http.Header) string {
  462. return header.Get("x-oss-copy-source-version-id")
  463. }
  464. func GetDeleteMark(header http.Header) bool {
  465. value := header.Get("x-oss-delete-marker")
  466. if strings.ToUpper(value) == "TRUE" {
  467. return true
  468. }
  469. return false
  470. }
  471. func GetQosDelayTime(header http.Header) string {
  472. return header.Get("x-oss-qos-delay-time")
  473. }