option.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  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, strings.ToLower(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. // TrafficLimitHeader is an option to set X-Oss-Traffic-Limit
  198. func TrafficLimitHeader(value int64) Option {
  199. return setHeader(HTTPHeaderOssTrafficLimit, strconv.FormatInt(value, 10))
  200. }
  201. // UserAgentHeader is an option to set HTTPHeaderUserAgent
  202. func UserAgentHeader(ua string) Option {
  203. return setHeader(HTTPHeaderUserAgent, ua)
  204. }
  205. // Delimiter is an option to set delimiler parameter
  206. func Delimiter(value string) Option {
  207. return addParam("delimiter", value)
  208. }
  209. // Marker is an option to set marker parameter
  210. func Marker(value string) Option {
  211. return addParam("marker", value)
  212. }
  213. // MaxKeys is an option to set maxkeys parameter
  214. func MaxKeys(value int) Option {
  215. return addParam("max-keys", strconv.Itoa(value))
  216. }
  217. // Prefix is an option to set prefix parameter
  218. func Prefix(value string) Option {
  219. return addParam("prefix", value)
  220. }
  221. // EncodingType is an option to set encoding-type parameter
  222. func EncodingType(value string) Option {
  223. return addParam("encoding-type", value)
  224. }
  225. // MaxUploads is an option to set max-uploads parameter
  226. func MaxUploads(value int) Option {
  227. return addParam("max-uploads", strconv.Itoa(value))
  228. }
  229. // KeyMarker is an option to set key-marker parameter
  230. func KeyMarker(value string) Option {
  231. return addParam("key-marker", value)
  232. }
  233. // VersionIdMarker is an option to set version-id-marker parameter
  234. func VersionIdMarker(value string) Option {
  235. return addParam("version-id-marker", value)
  236. }
  237. // VersionId is an option to set versionId parameter
  238. func VersionId(value string) Option {
  239. return addParam("versionId", value)
  240. }
  241. // TagKey is an option to set tag key parameter
  242. func TagKey(value string) Option {
  243. return addParam("tag-key", value)
  244. }
  245. // TagValue is an option to set tag value parameter
  246. func TagValue(value string) Option {
  247. return addParam("tag-value", value)
  248. }
  249. // UploadIDMarker is an option to set upload-id-marker parameter
  250. func UploadIDMarker(value string) Option {
  251. return addParam("upload-id-marker", value)
  252. }
  253. // MaxParts is an option to set max-parts parameter
  254. func MaxParts(value int) Option {
  255. return addParam("max-parts", strconv.Itoa(value))
  256. }
  257. // PartNumberMarker is an option to set part-number-marker parameter
  258. func PartNumberMarker(value int) Option {
  259. return addParam("part-number-marker", strconv.Itoa(value))
  260. }
  261. // DeleteObjectsQuiet false:DeleteObjects in verbose mode; true:DeleteObjects in quite mode. Default is false.
  262. func DeleteObjectsQuiet(isQuiet bool) Option {
  263. return addArg(deleteObjectsQuiet, isQuiet)
  264. }
  265. // StorageClass bucket storage class
  266. func StorageClass(value StorageClassType) Option {
  267. return addArg(storageClass, value)
  268. }
  269. // Checkpoint configuration
  270. type cpConfig struct {
  271. IsEnable bool
  272. FilePath string
  273. DirPath string
  274. }
  275. // Checkpoint sets the isEnable flag and checkpoint file path for DownloadFile/UploadFile.
  276. func Checkpoint(isEnable bool, filePath string) Option {
  277. return addArg(checkpointConfig, &cpConfig{IsEnable: isEnable, FilePath: filePath})
  278. }
  279. // CheckpointDir sets the isEnable flag and checkpoint dir path for DownloadFile/UploadFile.
  280. func CheckpointDir(isEnable bool, dirPath string) Option {
  281. return addArg(checkpointConfig, &cpConfig{IsEnable: isEnable, DirPath: dirPath})
  282. }
  283. // Routines DownloadFile/UploadFile routine count
  284. func Routines(n int) Option {
  285. return addArg(routineNum, n)
  286. }
  287. // InitCRC Init AppendObject CRC
  288. func InitCRC(initCRC uint64) Option {
  289. return addArg(initCRC64, initCRC)
  290. }
  291. // Progress set progress listener
  292. func Progress(listener ProgressListener) Option {
  293. return addArg(progressListener, listener)
  294. }
  295. // GetResponseHeader for get response http header
  296. func GetResponseHeader(respHeader *http.Header) Option {
  297. return addArg(responseHeader, respHeader)
  298. }
  299. // ResponseContentType is an option to set response-content-type param
  300. func ResponseContentType(value string) Option {
  301. return addParam("response-content-type", value)
  302. }
  303. // ResponseContentLanguage is an option to set response-content-language param
  304. func ResponseContentLanguage(value string) Option {
  305. return addParam("response-content-language", value)
  306. }
  307. // ResponseExpires is an option to set response-expires param
  308. func ResponseExpires(value string) Option {
  309. return addParam("response-expires", value)
  310. }
  311. // ResponseCacheControl is an option to set response-cache-control param
  312. func ResponseCacheControl(value string) Option {
  313. return addParam("response-cache-control", value)
  314. }
  315. // ResponseContentDisposition is an option to set response-content-disposition param
  316. func ResponseContentDisposition(value string) Option {
  317. return addParam("response-content-disposition", value)
  318. }
  319. // ResponseContentEncoding is an option to set response-content-encoding param
  320. func ResponseContentEncoding(value string) Option {
  321. return addParam("response-content-encoding", value)
  322. }
  323. // Process is an option to set x-oss-process param
  324. func Process(value string) Option {
  325. return addParam("x-oss-process", value)
  326. }
  327. // TrafficLimitParam is a option to set x-oss-traffic-limit
  328. func TrafficLimitParam(value int64) Option {
  329. return addParam("x-oss-traffic-limit", strconv.FormatInt(value, 10))
  330. }
  331. func setHeader(key string, value interface{}) Option {
  332. return func(params map[string]optionValue) error {
  333. if value == nil {
  334. return nil
  335. }
  336. params[key] = optionValue{value, optionHTTP}
  337. return nil
  338. }
  339. }
  340. func addParam(key string, value interface{}) Option {
  341. return func(params map[string]optionValue) error {
  342. if value == nil {
  343. return nil
  344. }
  345. params[key] = optionValue{value, optionParam}
  346. return nil
  347. }
  348. }
  349. func addArg(key string, value interface{}) Option {
  350. return func(params map[string]optionValue) error {
  351. if value == nil {
  352. return nil
  353. }
  354. params[key] = optionValue{value, optionArg}
  355. return nil
  356. }
  357. }
  358. func handleOptions(headers map[string]string, options []Option) error {
  359. params := map[string]optionValue{}
  360. for _, option := range options {
  361. if option != nil {
  362. if err := option(params); err != nil {
  363. return err
  364. }
  365. }
  366. }
  367. for k, v := range params {
  368. if v.Type == optionHTTP {
  369. headers[k] = v.Value.(string)
  370. }
  371. }
  372. return nil
  373. }
  374. func GetRawParams(options []Option) (map[string]interface{}, error) {
  375. // Option
  376. params := map[string]optionValue{}
  377. for _, option := range options {
  378. if option != nil {
  379. if err := option(params); err != nil {
  380. return nil, err
  381. }
  382. }
  383. }
  384. paramsm := map[string]interface{}{}
  385. // Serialize
  386. for k, v := range params {
  387. if v.Type == optionParam {
  388. vs := params[k]
  389. paramsm[k] = vs.Value.(string)
  390. }
  391. }
  392. return paramsm, nil
  393. }
  394. func FindOption(options []Option, param string, defaultVal interface{}) (interface{}, error) {
  395. params := map[string]optionValue{}
  396. for _, option := range options {
  397. if option != nil {
  398. if err := option(params); err != nil {
  399. return nil, err
  400. }
  401. }
  402. }
  403. if val, ok := params[param]; ok {
  404. return val.Value, nil
  405. }
  406. return defaultVal, nil
  407. }
  408. func IsOptionSet(options []Option, option string) (bool, interface{}, error) {
  409. params := map[string]optionValue{}
  410. for _, option := range options {
  411. if option != nil {
  412. if err := option(params); err != nil {
  413. return false, nil, err
  414. }
  415. }
  416. }
  417. if val, ok := params[option]; ok {
  418. return true, val.Value, nil
  419. }
  420. return false, nil, nil
  421. }
  422. func DeleteOption(options []Option, strKey string) []Option {
  423. var outOption []Option
  424. params := map[string]optionValue{}
  425. for _, option := range options {
  426. if option != nil {
  427. option(params)
  428. _, exist := params[strKey]
  429. if !exist {
  430. outOption = append(outOption, option)
  431. } else {
  432. delete(params, strKey)
  433. }
  434. }
  435. }
  436. return outOption
  437. }
  438. func GetRequestId(header http.Header) string {
  439. return header.Get("x-oss-request-id")
  440. }
  441. func GetVersionId(header http.Header) string {
  442. return header.Get("x-oss-version-id")
  443. }
  444. func GetCopySrcVersionId(header http.Header) string {
  445. return header.Get("x-oss-copy-source-version-id")
  446. }
  447. func GetDeleteMark(header http.Header) bool {
  448. value := header.Get("x-oss-delete-marker")
  449. if strings.ToUpper(value) == "TRUE" {
  450. return true
  451. }
  452. return false
  453. }
  454. func GetQosDelayTime(header http.Header) string {
  455. return header.Get("x-oss-qos-delay-time")
  456. }