option.go 15 KB

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