Skip to content

Commit 453ff54

Browse files
author
jojoliang
committed
add proxy demo
1 parent ad06e7a commit 453ff54

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

example/object/put_with_proxy.go

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"net"
7+
"net/http"
8+
"net/url"
9+
"os"
10+
"time"
11+
12+
"github.com/tencentyun/cos-go-sdk-v5"
13+
)
14+
15+
func log_status(err error) {
16+
if err == nil {
17+
return
18+
}
19+
if cos.IsNotFoundError(err) {
20+
// WARN
21+
fmt.Println("WARN: Resource is not existed")
22+
} else if e, ok := cos.IsCOSError(err); ok {
23+
fmt.Printf("ERROR: Code: %v\n", e.Code)
24+
fmt.Printf("ERROR: Message: %v\n", e.Message)
25+
fmt.Printf("ERROR: Resource: %v\n", e.Resource)
26+
fmt.Printf("ERROR: RequestId: %v\n", e.RequestID)
27+
// ERROR
28+
} else {
29+
fmt.Printf("ERROR: %v\n", err)
30+
// ERROR
31+
}
32+
}
33+
34+
func main() {
35+
// 存储桶名称,由bucketname-appid 组成,appid必须填入,可以在COS控制台查看存储桶名称。 https://console.cloud.tencent.com/cos5/bucket
36+
// 替换为用户的 region,存储桶region可以在COS控制台“存储桶概览”查看 https://console.cloud.tencent.com/ ,关于地域的详情见 https://cloud.tencent.com/document/product/436/6224 。
37+
u, _ := url.Parse("https://test-1259654469.cos.ap-guangzhou.myqcloud.com")
38+
b := &cos.BaseURL{BucketURL: u}
39+
40+
// 使用代理, 填写自己的代理地址
41+
proxyURL, _ := url.Parse("http://<hostname-or-ip>:7000")
42+
c := cos.NewClient(b, &http.Client{
43+
Transport: &cos.AuthorizationTransport{
44+
// 通过环境变量获取密钥
45+
// 环境变量 COS_SECRETID 表示用户的 SecretId,登录访问管理控制台查看密钥,https://console.cloud.tencent.com/cam/capi
46+
SecretID: os.Getenv("COS_SECRETID"),
47+
// 环境变量 COS_SECRETKEY 表示用户的 SecretKey,登录访问管理控制台查看密钥,https://console.cloud.tencent.com/cam/capi
48+
SecretKey: os.Getenv("COS_SECRETKEY"),
49+
// base on http.DefaultTransport
50+
Transport: &http.Transport{
51+
Proxy: http.ProxyURL(proxyURL), // 设置代理, DefaultTransport 默认代理是根据环境变量 https://pkg.go.dev/net/http#ProxyFromEnvironment
52+
DialContext: (&net.Dialer{
53+
Timeout: 30 * time.Second,
54+
KeepAlive: 30 * time.Second,
55+
DualStack: true,
56+
}).DialContext,
57+
MaxIdleConns: 100,
58+
IdleConnTimeout: 90 * time.Second,
59+
TLSHandshakeTimeout: 10 * time.Second,
60+
ExpectContinueTimeout: 1 * time.Second,
61+
// ResponseHeaderTimeout: 1 * time.Second,
62+
// MaxIdleConnsPerHost: 100,
63+
// MaxIdleConns: 100,
64+
},
65+
},
66+
})
67+
68+
// Case1 上传对象
69+
name := "test/example"
70+
// Case3 通过本地文件上传对象
71+
_, err := c.Object.PutFromFile(context.Background(), name, "./test", nil) // 请求的超时时间为 min{context超时时间, HTTP超时时间}
72+
log_status(err)
73+
}

0 commit comments

Comments
 (0)