Skip to content

Commit

Permalink
add proxy demo
Browse files Browse the repository at this point in the history
  • Loading branch information
jojoliang committed Jul 27, 2022
1 parent ad06e7a commit 453ff54
Showing 1 changed file with 73 additions and 0 deletions.
73 changes: 73 additions & 0 deletions example/object/put_with_proxy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package main

import (
"context"
"fmt"
"net"
"net/http"
"net/url"
"os"
"time"

"github.com/tencentyun/cos-go-sdk-v5"
)

func log_status(err error) {
if err == nil {
return
}
if cos.IsNotFoundError(err) {
// WARN
fmt.Println("WARN: Resource is not existed")
} else if e, ok := cos.IsCOSError(err); ok {
fmt.Printf("ERROR: Code: %v\n", e.Code)
fmt.Printf("ERROR: Message: %v\n", e.Message)
fmt.Printf("ERROR: Resource: %v\n", e.Resource)
fmt.Printf("ERROR: RequestId: %v\n", e.RequestID)
// ERROR
} else {
fmt.Printf("ERROR: %v\n", err)
// ERROR
}
}

func main() {
// 存储桶名称,由bucketname-appid 组成,appid必须填入,可以在COS控制台查看存储桶名称。 https://console.cloud.tencent.com/cos5/bucket
// 替换为用户的 region,存储桶region可以在COS控制台“存储桶概览”查看 https://console.cloud.tencent.com/ ,关于地域的详情见 https://cloud.tencent.com/document/product/436/6224 。
u, _ := url.Parse("https://test-1259654469.cos.ap-guangzhou.myqcloud.com")
b := &cos.BaseURL{BucketURL: u}

// 使用代理, 填写自己的代理地址
proxyURL, _ := url.Parse("http://<hostname-or-ip>:7000")
c := cos.NewClient(b, &http.Client{
Transport: &cos.AuthorizationTransport{
// 通过环境变量获取密钥
// 环境变量 COS_SECRETID 表示用户的 SecretId,登录访问管理控制台查看密钥,https://console.cloud.tencent.com/cam/capi
SecretID: os.Getenv("COS_SECRETID"),
// 环境变量 COS_SECRETKEY 表示用户的 SecretKey,登录访问管理控制台查看密钥,https://console.cloud.tencent.com/cam/capi
SecretKey: os.Getenv("COS_SECRETKEY"),
// base on http.DefaultTransport
Transport: &http.Transport{
Proxy: http.ProxyURL(proxyURL), // 设置代理, DefaultTransport 默认代理是根据环境变量 https://pkg.go.dev/net/http#ProxyFromEnvironment
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
// ResponseHeaderTimeout: 1 * time.Second,
// MaxIdleConnsPerHost: 100,
// MaxIdleConns: 100,
},
},
})

// Case1 上传对象
name := "test/example"
// Case3 通过本地文件上传对象
_, err := c.Object.PutFromFile(context.Background(), name, "./test", nil) // 请求的超时时间为 min{context超时时间, HTTP超时时间}
log_status(err)
}

0 comments on commit 453ff54

Please sign in to comment.