You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
1.6 KiB

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "net/url"
  7. "os"
  8. "time"
  9. "github.com/tencentyun/cos-go-sdk-v5"
  10. )
  11. type URLToken struct {
  12. SessionToken string `url:"x-cos-security-token,omitempty" header:"-"`
  13. }
  14. func main() {
  15. // 替换成您的临时密钥
  16. tak := os.Getenv("COS_SECRETID")
  17. tsk := os.Getenv("COS_SECRETKEY")
  18. token := &URLToken{
  19. SessionToken: "<token>",
  20. }
  21. u, _ := url.Parse("https://test-1259654469.cos.ap-guangzhou.myqcloud.com")
  22. b := &cos.BaseURL{BucketURL: u}
  23. c := cos.NewClient(b, &http.Client{})
  24. name := "exampleobject"
  25. ctx := context.Background()
  26. // 方法1 通过 tag 设置 x-cos-security-token
  27. // Get presigned
  28. presignedURL, err := c.Object.GetPresignedURL(ctx, http.MethodGet, name, tak, tsk, time.Hour, token)
  29. if err != nil {
  30. fmt.Printf("Error: %v\n", err)
  31. return
  32. }
  33. // Get object by presinged url
  34. resp, err := http.Get(presignedURL.String())
  35. if err != nil {
  36. fmt.Printf("Error: %v\n", err)
  37. }
  38. defer resp.Body.Close()
  39. fmt.Println(presignedURL.String())
  40. fmt.Printf("resp:%v\n", resp)
  41. // 方法2 通过 PresignedURLOptions 设置 x-cos-security-token
  42. opt := &cos.PresignedURLOptions{
  43. Query: &url.Values{},
  44. Header: &http.Header{},
  45. }
  46. opt.Query.Add("x-cos-security-token", "<token>")
  47. // Get presigned
  48. presignedURL, err = c.Object.GetPresignedURL(ctx, http.MethodGet, name, tak, tsk, time.Hour, opt)
  49. if err != nil {
  50. fmt.Printf("Error: %v\n", err)
  51. return
  52. }
  53. // Get object by presinged url
  54. resp, err = http.Get(presignedURL.String())
  55. if err != nil {
  56. fmt.Printf("Error: %v\n", err)
  57. }
  58. defer resp.Body.Close()
  59. fmt.Println(presignedURL.String())
  60. fmt.Printf("resp:%v\n", resp)
  61. }