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.

75 lines
1.9 KiB

  1. package main
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "net/url"
  9. "os"
  10. "strings"
  11. "github.com/tencentyun/cos-go-sdk-v5"
  12. "github.com/tencentyun/cos-go-sdk-v5/debug"
  13. )
  14. func log_status(err error) {
  15. if err == nil {
  16. return
  17. }
  18. if cos.IsNotFoundError(err) {
  19. // WARN
  20. fmt.Println("WARN: Resource is not existed")
  21. } else if e, ok := cos.IsCOSError(err); ok {
  22. fmt.Printf("ERROR: Code: %v\n", e.Code)
  23. fmt.Printf("ERROR: Message: %v\n", e.Message)
  24. fmt.Printf("ERROR: Resource: %v\n", e.Resource)
  25. fmt.Printf("ERROR: RequestId: %v\n", e.RequestID)
  26. // ERROR
  27. } else {
  28. fmt.Printf("ERROR: %v\n", err)
  29. // ERROR
  30. }
  31. }
  32. func main() {
  33. u, _ := url.Parse("https://test-1259654469.cos.ap-guangzhou.myqcloud.com")
  34. b := &cos.BaseURL{BucketURL: u}
  35. c := cos.NewClient(b, &http.Client{
  36. Transport: &cos.AuthorizationTransport{
  37. SecretID: os.Getenv("COS_SECRETID"),
  38. SecretKey: os.Getenv("COS_SECRETKEY"),
  39. Transport: &debug.DebugRequestTransport{
  40. RequestHeader: true,
  41. // Notice when put a large file and set need the request body, might happend out of memory error.
  42. RequestBody: false,
  43. ResponseHeader: true,
  44. ResponseBody: true,
  45. },
  46. },
  47. })
  48. opt := &cos.ObjectPutOptions{
  49. ObjectPutHeaderOptions: &cos.ObjectPutHeaderOptions{
  50. ContentType: "text/html",
  51. XCosServerSideEncryption: "AES256",
  52. },
  53. ACLHeaderOptions: &cos.ACLHeaderOptions{},
  54. }
  55. name := "PutFromGoWithSSE-COS"
  56. content := "Put Object From Go With SSE-COS"
  57. f := strings.NewReader(content)
  58. _, err := c.Object.Put(context.Background(), name, f, opt)
  59. log_status(err)
  60. getopt := &cos.ObjectGetOptions{}
  61. var resp *cos.Response
  62. resp, err = c.Object.Get(context.Background(), name, getopt)
  63. log_status(err)
  64. bodyBytes, _ := ioutil.ReadAll(resp.Body)
  65. bodyContent := string(bodyBytes)
  66. if bodyContent != content {
  67. log_status(errors.New("Content inconsistency"))
  68. }
  69. }