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.

145 lines
3.8 KiB

  1. package main
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "net/url"
  8. "os"
  9. "strings"
  10. "github.com/QcloudApi/qcloud_sign_golang"
  11. "github.com/tencentyun/cos-go-sdk-v5"
  12. "github.com/tencentyun/cos-go-sdk-v5/debug"
  13. )
  14. // Use Qcloud api github.com/QcloudApi/qcloud_sign_golang
  15. // doc https://cloud.tencent.com/document/product/436/14048
  16. type Credent struct {
  17. SessionToken string `json:"sessionToken"`
  18. TmpSecretID string `json:"tmpSecretId"`
  19. TmpSecretKey string `json:"tmpSecretKey"`
  20. }
  21. type PolicyStatement struct {
  22. Action []string `json:"action,omitempty"`
  23. Effect string `json:"effect,omitempty"`
  24. Resource []string `json:"resource,omitempty"`
  25. Condition map[string]map[string]interface{} `json:"condition,omitempty"`
  26. }
  27. type CAMPolicy struct {
  28. Statement []PolicyStatement `json:"statement,omitempty"`
  29. Version string `json:"version,omitempty"`
  30. Principal map[string][]string `json:"principal,omitempty"`
  31. }
  32. // Data data in sts response body
  33. type Data struct {
  34. Credentials Credent `json:"credentials"`
  35. }
  36. // Response sts response body
  37. // In qcloud_sign_golang this response only return ak, sk and token
  38. type Response struct {
  39. Dat Data `json:"data"`
  40. }
  41. func main() {
  42. // 在环境变量中设置您的 SecretId 和 SecretKey
  43. secretID := os.Getenv("COS_SECRETID")
  44. secretKey := os.Getenv("COS_SECRETKEY")
  45. appid := "1259654469" //替换成您的APPID
  46. bucket := "test-1259654469" //替换成您的bucket,格式:<bucketname-APPID>
  47. // 配置
  48. config := map[string]interface{}{"secretId": secretID, "secretKey": secretKey, "debug": false}
  49. policy := &CAMPolicy{
  50. Statement: []PolicyStatement{
  51. PolicyStatement{
  52. Action: []string{
  53. "name/cos:PostObject",
  54. "name/cos:PutObject",
  55. },
  56. Effect: "allow",
  57. Resource: []string{
  58. //这里改成允许的路径前缀,可以根据自己网站的用户登录态判断允许上传的具体路径,例子: a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
  59. "qcs::cos:ap-guangzhou:uid/" + appid + ":" + bucket + "/exampleobject",
  60. },
  61. },
  62. },
  63. Version: "2.0",
  64. }
  65. bPolicy, err := json.Marshal(policy)
  66. if err != nil {
  67. fmt.Print("Error.", err)
  68. return
  69. }
  70. policyStr := string(bPolicy)
  71. // 请求参数
  72. params := map[string]interface{}{
  73. "Region": "gz",
  74. "Action": "GetFederationToken",
  75. "name": "test",
  76. "policy": policyStr,
  77. }
  78. // 发送请求
  79. retData, err := QcloudApi.SendRequest("sts", params, config)
  80. if err != nil {
  81. fmt.Print("Error.", err)
  82. return
  83. }
  84. r := &Response{}
  85. err = json.Unmarshal([]byte(retData), r)
  86. if err != nil {
  87. fmt.Println(err)
  88. return
  89. }
  90. //获取临时ak、sk、token
  91. tAk := r.Dat.Credentials.TmpSecretID
  92. tSk := r.Dat.Credentials.TmpSecretKey
  93. token := r.Dat.Credentials.SessionToken
  94. u, _ := url.Parse("https://" + bucket + ".cos.ap-guangzhou.myqcloud.com")
  95. b := &cos.BaseURL{BucketURL: u}
  96. c := cos.NewClient(b, &http.Client{
  97. Transport: &cos.AuthorizationTransport{
  98. SecretID: tAk,
  99. SecretKey: tSk,
  100. SessionToken: token,
  101. Transport: &debug.DebugRequestTransport{
  102. RequestHeader: true,
  103. RequestBody: true,
  104. ResponseHeader: true,
  105. ResponseBody: true,
  106. },
  107. },
  108. })
  109. name := "exampleobject"
  110. f := strings.NewReader("test")
  111. _, err = c.Object.Put(context.Background(), name, f, nil)
  112. if err != nil {
  113. panic(err)
  114. }
  115. name = "exampleobject"
  116. f = strings.NewReader("test xxx")
  117. opt := &cos.ObjectPutOptions{
  118. ObjectPutHeaderOptions: &cos.ObjectPutHeaderOptions{
  119. ContentType: "text/html",
  120. },
  121. ACLHeaderOptions: &cos.ACLHeaderOptions{
  122. //XCosACL: "public-read",
  123. XCosACL: "private",
  124. },
  125. }
  126. _, err = c.Object.Put(context.Background(), name, f, opt)
  127. if err != nil {
  128. panic(err)
  129. }
  130. }