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.

96 lines
2.3 KiB

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/tencentyun/cos-go-sdk-v5"
  6. "github.com/tencentyun/cos-go-sdk-v5/debug"
  7. "github.com/tencentyun/qcloud-cos-sts-sdk/go"
  8. "net/http"
  9. "net/url"
  10. "os"
  11. "strings"
  12. "time"
  13. )
  14. func main() {
  15. appid := "1259654469"
  16. bucket := "test-1259654469"
  17. c := sts.NewClient(
  18. os.Getenv("COS_SECRETID"),
  19. os.Getenv("COS_SECRETKEY"),
  20. nil,
  21. )
  22. opt := &sts.CredentialOptions{
  23. DurationSeconds: int64(time.Hour.Seconds()),
  24. Region: "ap-guangzhou",
  25. Policy: &sts.CredentialPolicy{
  26. Statement: []sts.CredentialPolicyStatement{
  27. {
  28. Action: []string{
  29. "name/cos:PostObject",
  30. "name/cos:PutObject",
  31. "name/cos:GetObject",
  32. },
  33. Effect: "allow",
  34. Resource: []string{
  35. //这里改成允许的路径前缀,可以根据自己网站的用户登录态判断允许上传的具体路径,例子: a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
  36. "qcs::cos:ap-guangzhou:uid/" + appid + ":" + bucket + "/exampleobject",
  37. },
  38. },
  39. },
  40. },
  41. }
  42. res, err := c.GetCredential(opt)
  43. if err != nil {
  44. panic(err)
  45. }
  46. fmt.Printf("%+v\n", res.Credentials)
  47. //获取临时ak、sk、token
  48. tAk := res.Credentials.TmpSecretID
  49. tSk := res.Credentials.TmpSecretKey
  50. token := res.Credentials.SessionToken
  51. u, _ := url.Parse("https://" + bucket + ".cos.ap-guangzhou.myqcloud.com")
  52. b := &cos.BaseURL{BucketURL: u}
  53. client := cos.NewClient(b, &http.Client{
  54. Transport: &cos.AuthorizationTransport{
  55. // 使用临时密钥
  56. SecretID: tAk,
  57. SecretKey: tSk,
  58. SessionToken: token,
  59. Transport: &debug.DebugRequestTransport{
  60. RequestHeader: true,
  61. RequestBody: true,
  62. ResponseHeader: true,
  63. ResponseBody: true,
  64. },
  65. },
  66. })
  67. name := "exampleobject"
  68. f := strings.NewReader("test")
  69. _, err = client.Object.Put(context.Background(), name, f, nil)
  70. if err != nil {
  71. panic(err)
  72. }
  73. name = "exampleobject"
  74. f = strings.NewReader("test xxx")
  75. optc := &cos.ObjectPutOptions{
  76. ObjectPutHeaderOptions: &cos.ObjectPutHeaderOptions{
  77. ContentType: "text/html",
  78. },
  79. ACLHeaderOptions: &cos.ACLHeaderOptions{
  80. //XCosACL: "public-read",
  81. XCosACL: "private",
  82. },
  83. }
  84. _, err = client.Object.Put(context.Background(), name, f, optc)
  85. if err != nil {
  86. panic(err)
  87. }
  88. }