option.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. package oss
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strconv"
  6. "strings"
  7. "time"
  8. )
  9. type optionType string
  10. const (
  11. optionParam optionType = "HTTPParameter" // URL parameter
  12. optionHTTP optionType = "HTTPHeader" // HTTP header
  13. optionArg optionType = "FuncArgument" // Function argument
  14. )
  15. const (
  16. deleteObjectsQuiet = "delete-objects-quiet"
  17. routineNum = "x-routine-num"
  18. checkpointConfig = "x-cp-config"
  19. initCRC64 = "init-crc64"
  20. progressListener = "x-progress-listener"
  21. storageClass = "storage-class"
  22. )
  23. type (
  24. optionValue struct {
  25. Value interface{}
  26. Type optionType
  27. }
  28. // Option HTTP option
  29. Option func(map[string]optionValue) error
  30. )
  31. // ACL is an option to set X-Oss-Acl header
  32. func ACL(acl ACLType) Option {
  33. return setHeader(HTTPHeaderOssACL, string(acl))
  34. }
  35. // ContentType is an option to set Content-Type header
  36. func ContentType(value string) Option {
  37. return setHeader(HTTPHeaderContentType, value)
  38. }
  39. // ContentLength is an option to set Content-Length header
  40. func ContentLength(length int64) Option {
  41. return setHeader(HTTPHeaderContentLength, strconv.FormatInt(length, 10))
  42. }
  43. // CacheControl is an option to set Cache-Control header
  44. func CacheControl(value string) Option {
  45. return setHeader(HTTPHeaderCacheControl, value)
  46. }
  47. // ContentDisposition is an option to set Content-Disposition header
  48. func ContentDisposition(value string) Option {
  49. return setHeader(HTTPHeaderContentDisposition, value)
  50. }
  51. // ContentEncoding is an option to set Content-Encoding header
  52. func ContentEncoding(value string) Option {
  53. return setHeader(HTTPHeaderContentEncoding, value)
  54. }
  55. // ContentLanguage is an option to set Content-Language header
  56. func ContentLanguage(value string) Option {
  57. return setHeader(HTTPHeaderContentLanguage, value)
  58. }
  59. // ContentMD5 is an option to set Content-MD5 header
  60. func ContentMD5(value string) Option {
  61. return setHeader(HTTPHeaderContentMD5, value)
  62. }
  63. // Expires is an option to set Expires header
  64. func Expires(t time.Time) Option {
  65. return setHeader(HTTPHeaderExpires, t.Format(http.TimeFormat))
  66. }
  67. // Meta is an option to set Meta header
  68. func Meta(key, value string) Option {
  69. return setHeader(HTTPHeaderOssMetaPrefix+key, value)
  70. }
  71. // Range is an option to set Range header, [start, end]
  72. func Range(start, end int64) Option {
  73. return setHeader(HTTPHeaderRange, fmt.Sprintf("bytes=%d-%d", start, end))
  74. }
  75. // NormalizedRange is an option to set Range header, such as 1024-2048 or 1024- or -2048
  76. func NormalizedRange(nr string) Option {
  77. return setHeader(HTTPHeaderRange, fmt.Sprintf("bytes=%s", strings.TrimSpace(nr)))
  78. }
  79. // AcceptEncoding is an option to set Accept-Encoding header
  80. func AcceptEncoding(value string) Option {
  81. return setHeader(HTTPHeaderAcceptEncoding, value)
  82. }
  83. // IfModifiedSince is an option to set If-Modified-Since header
  84. func IfModifiedSince(t time.Time) Option {
  85. return setHeader(HTTPHeaderIfModifiedSince, t.Format(http.TimeFormat))
  86. }
  87. // IfUnmodifiedSince is an option to set If-Unmodified-Since header
  88. func IfUnmodifiedSince(t time.Time) Option {
  89. return setHeader(HTTPHeaderIfUnmodifiedSince, t.Format(http.TimeFormat))
  90. }
  91. // IfMatch is an option to set If-Match header
  92. func IfMatch(value string) Option {
  93. return setHeader(HTTPHeaderIfMatch, value)
  94. }
  95. // IfNoneMatch is an option to set IfNoneMatch header
  96. func IfNoneMatch(value string) Option {
  97. return setHeader(HTTPHeaderIfNoneMatch, value)
  98. }
  99. // CopySource is an option to set X-Oss-Copy-Source header
  100. func CopySource(sourceBucket, sourceObject string) Option {
  101. return setHeader(HTTPHeaderOssCopySource, "/"+sourceBucket+"/"+sourceObject)
  102. }
  103. // CopySourceRange is an option to set X-Oss-Copy-Source header
  104. func CopySourceRange(startPosition, partSize int64) Option {
  105. val := "bytes=" + strconv.FormatInt(startPosition, 10) + "-" +
  106. strconv.FormatInt((startPosition+partSize-1), 10)
  107. return setHeader(HTTPHeaderOssCopySourceRange, val)
  108. }
  109. // CopySourceIfMatch is an option to set X-Oss-Copy-Source-If-Match header
  110. func CopySourceIfMatch(value string) Option {
  111. return setHeader(HTTPHeaderOssCopySourceIfMatch, value)
  112. }
  113. // CopySourceIfNoneMatch is an option to set X-Oss-Copy-Source-If-None-Match header
  114. func CopySourceIfNoneMatch(value string) Option {
  115. return setHeader(HTTPHeaderOssCopySourceIfNoneMatch, value)
  116. }
  117. // CopySourceIfModifiedSince is an option to set X-Oss-CopySource-If-Modified-Since header
  118. func CopySourceIfModifiedSince(t time.Time) Option {
  119. return setHeader(HTTPHeaderOssCopySourceIfModifiedSince, t.Format(http.TimeFormat))
  120. }
  121. // CopySourceIfUnmodifiedSince is an option to set X-Oss-Copy-Source-If-Unmodified-Since header
  122. func CopySourceIfUnmodifiedSince(t time.Time) Option {
  123. return setHeader(HTTPHeaderOssCopySourceIfUnmodifiedSince, t.Format(http.TimeFormat))
  124. }
  125. // MetadataDirective is an option to set X-Oss-Metadata-Directive header
  126. func MetadataDirective(directive MetadataDirectiveType) Option {
  127. return setHeader(HTTPHeaderOssMetadataDirective, string(directive))
  128. }
  129. // ServerSideEncryption is an option to set X-Oss-Server-Side-Encryption header
  130. func ServerSideEncryption(value string) Option {
  131. return setHeader(HTTPHeaderOssServerSideEncryption, value)
  132. }
  133. // ServerSideEncryptionKeyID is an option to set X-Oss-Server-Side-Encryption-Key-Id header
  134. func ServerSideEncryptionKeyID(value string) Option {
  135. return setHeader(HTTPHeaderOssServerSideEncryptionKeyID, value)
  136. }
  137. // ObjectACL is an option to set X-Oss-Object-Acl header
  138. func ObjectACL(acl ACLType) Option {
  139. return setHeader(HTTPHeaderOssObjectACL, string(acl))
  140. }
  141. // symlinkTarget is an option to set X-Oss-Symlink-Target
  142. func symlinkTarget(targetObjectKey string) Option {
  143. return setHeader(HTTPHeaderOssSymlinkTarget, targetObjectKey)
  144. }
  145. // Origin is an option to set Origin header
  146. func Origin(value string) Option {
  147. return setHeader(HTTPHeaderOrigin, value)
  148. }
  149. // ObjectStorageClass is an option to set the storage class of object
  150. func ObjectStorageClass(storageClass StorageClassType) Option {
  151. return setHeader(HTTPHeaderOssStorageClass, string(storageClass))
  152. }
  153. // Callback is an option to set callback values
  154. func Callback(callback string) Option {
  155. return setHeader(HTTPHeaderOssCallback, callback)
  156. }
  157. // CallbackVar is an option to set callback user defined values
  158. func CallbackVar(callbackVar string) Option {
  159. return setHeader(HTTPHeaderOssCallbackVar, callbackVar)
  160. }
  161. // RequestPayer is an option to set payer who pay for the request
  162. func RequestPayer(payerType PayerType) Option {
  163. return setHeader(HTTPHeaderOSSRequester, string(payerType))
  164. }
  165. // Delimiter is an option to set delimiler parameter
  166. func Delimiter(value string) Option {
  167. return addParam("delimiter", value)
  168. }
  169. // Marker is an option to set marker parameter
  170. func Marker(value string) Option {
  171. return addParam("marker", value)
  172. }
  173. // MaxKeys is an option to set maxkeys parameter
  174. func MaxKeys(value int) Option {
  175. return addParam("max-keys", strconv.Itoa(value))
  176. }
  177. // Prefix is an option to set prefix parameter
  178. func Prefix(value string) Option {
  179. return addParam("prefix", value)
  180. }
  181. // EncodingType is an option to set encoding-type parameter
  182. func EncodingType(value string) Option {
  183. return addParam("encoding-type", value)
  184. }
  185. // MaxUploads is an option to set max-uploads parameter
  186. func MaxUploads(value int) Option {
  187. return addParam("max-uploads", strconv.Itoa(value))
  188. }
  189. // KeyMarker is an option to set key-marker parameter
  190. func KeyMarker(value string) Option {
  191. return addParam("key-marker", value)
  192. }
  193. // UploadIDMarker is an option to set upload-id-marker parameter
  194. func UploadIDMarker(value string) Option {
  195. return addParam("upload-id-marker", value)
  196. }
  197. // MaxParts is an option to set max-parts parameter
  198. func MaxParts(value int) Option {
  199. return addParam("max-parts", strconv.Itoa(value))
  200. }
  201. // PartNumberMarker is an option to set part-number-marker parameter
  202. func PartNumberMarker(value int) Option {
  203. return addParam("part-number-marker", strconv.Itoa(value))
  204. }
  205. // DeleteObjectsQuiet false:DeleteObjects in verbose mode; true:DeleteObjects in quite mode. Default is false.
  206. func DeleteObjectsQuiet(isQuiet bool) Option {
  207. return addArg(deleteObjectsQuiet, isQuiet)
  208. }
  209. // StorageClass bucket storage class
  210. func StorageClass(value StorageClassType) Option {
  211. return addArg(storageClass, value)
  212. }
  213. // Checkpoint configuration
  214. type cpConfig struct {
  215. IsEnable bool
  216. FilePath string
  217. DirPath string
  218. }
  219. // Checkpoint sets the isEnable flag and checkpoint file path for DownloadFile/UploadFile.
  220. func Checkpoint(isEnable bool, filePath string) Option {
  221. return addArg(checkpointConfig, &cpConfig{IsEnable: isEnable, FilePath: filePath})
  222. }
  223. // CheckpointDir sets the isEnable flag and checkpoint dir path for DownloadFile/UploadFile.
  224. func CheckpointDir(isEnable bool, dirPath string) Option {
  225. return addArg(checkpointConfig, &cpConfig{IsEnable: isEnable, DirPath: dirPath})
  226. }
  227. // Routines DownloadFile/UploadFile routine count
  228. func Routines(n int) Option {
  229. return addArg(routineNum, n)
  230. }
  231. // InitCRC Init AppendObject CRC
  232. func InitCRC(initCRC uint64) Option {
  233. return addArg(initCRC64, initCRC)
  234. }
  235. // Progress set progress listener
  236. func Progress(listener ProgressListener) Option {
  237. return addArg(progressListener, listener)
  238. }
  239. // ResponseContentType is an option to set response-content-type param
  240. func ResponseContentType(value string) Option {
  241. return addParam("response-content-type", value)
  242. }
  243. // ResponseContentLanguage is an option to set response-content-language param
  244. func ResponseContentLanguage(value string) Option {
  245. return addParam("response-content-language", value)
  246. }
  247. // ResponseExpires is an option to set response-expires param
  248. func ResponseExpires(value string) Option {
  249. return addParam("response-expires", value)
  250. }
  251. // ResponseCacheControl is an option to set response-cache-control param
  252. func ResponseCacheControl(value string) Option {
  253. return addParam("response-cache-control", value)
  254. }
  255. // ResponseContentDisposition is an option to set response-content-disposition param
  256. func ResponseContentDisposition(value string) Option {
  257. return addParam("response-content-disposition", value)
  258. }
  259. // ResponseContentEncoding is an option to set response-content-encoding param
  260. func ResponseContentEncoding(value string) Option {
  261. return addParam("response-content-encoding", value)
  262. }
  263. // Process is an option to set x-oss-process param
  264. func Process(value string) Option {
  265. return addParam("x-oss-process", value)
  266. }
  267. func setHeader(key string, value interface{}) Option {
  268. return func(params map[string]optionValue) error {
  269. if value == nil {
  270. return nil
  271. }
  272. params[key] = optionValue{value, optionHTTP}
  273. return nil
  274. }
  275. }
  276. func addParam(key string, value interface{}) Option {
  277. return func(params map[string]optionValue) error {
  278. if value == nil {
  279. return nil
  280. }
  281. params[key] = optionValue{value, optionParam}
  282. return nil
  283. }
  284. }
  285. func addArg(key string, value interface{}) Option {
  286. return func(params map[string]optionValue) error {
  287. if value == nil {
  288. return nil
  289. }
  290. params[key] = optionValue{value, optionArg}
  291. return nil
  292. }
  293. }
  294. func handleOptions(headers map[string]string, options []Option) error {
  295. params := map[string]optionValue{}
  296. for _, option := range options {
  297. if option != nil {
  298. if err := option(params); err != nil {
  299. return err
  300. }
  301. }
  302. }
  303. for k, v := range params {
  304. if v.Type == optionHTTP {
  305. headers[k] = v.Value.(string)
  306. }
  307. }
  308. return nil
  309. }
  310. func getRawParams(options []Option) (map[string]interface{}, error) {
  311. // Option
  312. params := map[string]optionValue{}
  313. for _, option := range options {
  314. if option != nil {
  315. if err := option(params); err != nil {
  316. return nil, err
  317. }
  318. }
  319. }
  320. paramsm := map[string]interface{}{}
  321. // Serialize
  322. for k, v := range params {
  323. if v.Type == optionParam {
  324. vs := params[k]
  325. paramsm[k] = vs.Value.(string)
  326. }
  327. }
  328. return paramsm, nil
  329. }
  330. func findOption(options []Option, param string, defaultVal interface{}) (interface{}, error) {
  331. params := map[string]optionValue{}
  332. for _, option := range options {
  333. if option != nil {
  334. if err := option(params); err != nil {
  335. return nil, err
  336. }
  337. }
  338. }
  339. if val, ok := params[param]; ok {
  340. return val.Value, nil
  341. }
  342. return defaultVal, nil
  343. }
  344. func isOptionSet(options []Option, option string) (bool, interface{}, error) {
  345. params := map[string]optionValue{}
  346. for _, option := range options {
  347. if option != nil {
  348. if err := option(params); err != nil {
  349. return false, nil, err
  350. }
  351. }
  352. }
  353. if val, ok := params[option]; ok {
  354. return true, val.Value, nil
  355. }
  356. return false, nil, nil
  357. }