### Install SDK Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Instructions on how to download and install the KS3 Go SDK using go get. ```APIDOC ## Install SDK * Installation Method: ```go go get github.com/ks3sdklib/aws-sdk-go ``` * SDK download can be found at [Github/SDK](https://github.com/ks3sdklib/aws-sdk-go). * Refer to [Github/test](https://github.com/ks3sdklib/aws-sdk-go/blob/master/test/ks3_test.go) for usage demos. ``` -------------------------------- ### Install KS3 Go SDK Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Use 'go get' to install the KS3 Go SDK. Refer to the GitHub repository for the latest version and usage examples. ```go go get github.com/ks3sdklib/aws-sdk-go ``` -------------------------------- ### Initialize Client Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Code example for initializing the KS3 client with credentials and configuration. ```APIDOC ## Initialize Client 1. Import necessary packages: ```go import( "github.com/ks3sdklib/aws-sdk-go/aws" "github.com/ks3sdklib/aws-sdk-go/aws/credentials" "github.com/ks3sdklib/aws-sdk-go/service/s3" ) ``` 2. Initialize the client: ```go credentials := credentials.NewStaticCredentials("","","") client := s3.New(&aws.Config{ Region: "BEIJING", Credentials: credentials, Endpoint:"ks3-cn-beijingcs.ksyun.com",// KS3 address DisableSSL:true,// Whether to disable https LogLevel:1,// Whether to enable logging, 0 for off, 1 for on // If this parameter is not effective, it is recommended to update to the latest version (>=1.0.21). S3ForcePathStyle:false,// Whether to force the use of path style access, default is not to use, true to enable LogHTTPBody:true,// Whether to log the HTTP request body Logger:os.Stdout,// Location for logging DomainMode: true, // Whether to enable custom bucket domain binding, when enabled, S3ForcePathStyle is not effective. }) ``` > Note: > * [Relationship between endpoint and Region](https://docs.ksyun.com/documents/6761) ``` -------------------------------- ### Create Bucket Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Example of how to create a new bucket using the KS3 Go SDK. ```APIDOC ## Create Bucket ```go func CreateBucket(svc *s3.S3) { resp, err := svc.CreateBucket(&s3.CreateBucketInput{ ACL: aws.String("public-read"),// Permissions Bucket: aws.String("bucket-name"), ProjectId: aws.String("project-id"),// Project ID }) if err != nil { if awsErr, ok := err.(awserr.Error); ok { fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) if reqErr, ok := err.(awserr.RequestFailure); ok { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { fmt.Println(err.Error()) } } fmt.Println("Result: \n", awsutil.StringValue(resp)) } ``` ``` -------------------------------- ### Get Bucket Mirror Rules with KS3 Go SDK Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Retrieves the configured mirror source rules for a specified bucket. This is useful for auditing or verifying current mirror settings. ```go //获取镜像回源规则 func GetBucketMirrorRules() { params := &s3.GetBucketMirrorInput{ Bucket: aws.String(BucketName), } resp, _ := client.GetBucketMirror(params) fmt.Println("resp.code is:", resp.HttpCode) fmt.Println("resp.Header is:", resp.Header) // Pretty-print the response data. var bodyStr = string(resp.Body[:]) fmt.Println("resp.Body is:", bodyStr) } ``` -------------------------------- ### Get Object Tagging Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Retrieves the tags associated with an object in KS3. ```APIDOC ## GetObjectTag ### Description Retrieves the tags associated with an object in KS3. ### Method func GetObjectTag(svc *s3.S3) { params := &s3.GetObjectTaggingInput{ Bucket: aws.String(bucketname), // Required Key: aws.String(key), } resp, err := client.GetObjectTagging(params) if err != nil { if awsErr, ok := err.(awserr.Error); ok { fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) if reqErr, ok := err.(awserr.RequestFailure); ok { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { fmt.Println(err.Error()) } } fmt.Println("结果:\n", awsutil.StringValue(resp)) } ### Parameters - Bucket (string) - Required - The bucket name. - Key (string) - Required - The object key. ``` -------------------------------- ### Get Object Tags with KS3 Go SDK Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Retrieves tags associated with a specific object in KS3. The function takes an S3 client and object details as input. ```go /** 获取对象标签 */ func GetObjectTag(svc *s3.S3) { params := &s3.GetObjectTaggingInput{ Bucket: aws.String(bucketname), // Required Key: aws.String(key), } resp, err := client.GetObjectTagging(params) if err != nil { if awsErr, ok := err.(awserr.Error); ok { fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) if reqErr, ok := err.(awserr.RequestFailure); ok { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { fmt.Println(err.Error()) } } fmt.Println("结果:\n", awsutil.StringValue(resp)) } ``` -------------------------------- ### Get Object Metadata with KS3 Go SDK Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Retrieves the metadata for a specific object in a bucket without downloading the object's content. Useful for checking object properties like size, content type, and last modified date. ```go func headObj(svc *s3.S3) { input := s3.HeadObjectInput{ Bucket: aws.String(bucketname), Key: aws.String(key), } resp, err := client.HeadObject(&input) if err != nil { if awsErr, ok := err.(awserr.Error); ok { fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) if reqErr, ok := err.(awserr.RequestFailure); ok { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { fmt.Println(err.Error()) } } fmt.Println("结果:\n", awsutil.StringValue(resp)) } ``` -------------------------------- ### Initialize KS3 Client Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Initialize the KS3 client with your Access Key ID, Secret Access Key, region, endpoint, and other configuration options. Ensure your SDK version is up-to-date for full functionality. ```go credentials := credentials.NewStaticCredentials("",""," இயந்திர") client := s3.New(&aws.Config{ Region: "BEIJING", Credentials: credentials, Endpoint:"ks3-cn-beijingcs.ksyun.com",//ks3地址 DisableSSL:true,//是否禁用https LogLevel:1,//是否开启日志,0为关闭日志,1为开启日志 //如果此参数没生效,建议更新到最新的版本(>=1.0.21)即可。 S3ForcePathStyle:false,//是否强制使用path style方式访问,默认不使用,true开启 LogHTTPBody:true,//是否把HTTP请求body打入日志 Logger:os.Stdout,//打日志的位置 DomainMode: true, //是否开启自定义bucket绑定域名,当开启时 S3ForcePathStyle 参数不生效。 }) ``` -------------------------------- ### Download File with KS3 Go SDK Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Downloads an object from a specified bucket and key. Reads and prints the first 20 bytes of the object's body, demonstrating basic download functionality. ```go params := &s3.GetObjectInput{ Bucket: aws.String("BucketName"), // bucket名称 Key: aws.String("ObjectKey"), // object key } resp, err := client.GetObject(params) if err != nil{ panic(err) } //读取返回结果中body的前20个字节 b := make([]byte, 20) n, err := resp.Body.Read(b) fmt.Printf("% -20s %-2v %v\n", b[:n], n, err) ``` -------------------------------- ### Import Necessary Packages for KS3 Client Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Import the required packages from the aws-sdk-go library to initialize the KS3 client. ```go import( "github.com/ks3sdklib/aws-sdk-go/aws" "github.com/ks3sdklib/aws-sdk-go/aws/credentials" "github.com/ks3sdklib/aws-sdk-go/service/s3" ) ``` -------------------------------- ### Create a Bucket with Specified ACL and Project ID Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 This function demonstrates how to create a new bucket in KS3. It allows setting the Access Control List (ACL) and the Project ID for the bucket. Error handling for AWS-specific errors is included. ```go func CreateBucket(svc *s3.S3) { resp, err := svc.CreateBucket(&s3.CreateBucketInput{ ACL: aws.String("public-read"),//权限 Bucket: aws.String("bucket"), ProjectId: aws.String("123123"),//项目制id }) if err != nil { if awsErr, ok := err.(awserr.Error); ok { fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) if reqErr, ok := err.(awserr.RequestFailure); ok { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { fmt.Println(err.Error()) } } fmt.Println("结果:\n", awsutil.StringValue(resp)) } ``` -------------------------------- ### Set Bucket Mirror Rules with KS3 Go SDK Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Configures mirror source rules for a bucket, supporting both asynchronous and synchronous mirroring with various settings like source URLs, ACL permissions, and match conditions. ```go func PutBucketMirrorRules() { params := &s3.PutBucketMirrorInput{ Bucket: aws.String(BucketName), // 桶名,必填字段 BucketMirror: &s3.BucketMirror{ Version: aws.String("V3"),//回源规则版本 UseDefaultRobots: aws.Boolean(false),//是否使用默认的robots.txt //异步回源规则,设置源站url、ACL权限 AsyncMirrorRule: &s3.AsyncMirrorRule{ MirrorUrls: []*string{ aws.String("http://abc.om"), aws.String("http://wps.om"), }, //SavingSetting: &s3.SavingSetting{ // ACL: "private", //}, }, //同步回源规则,设置触发条件(http_codes和文件前缀)、源站url、query string是否透传、是否follow 302/301、header配置、ACL权限 SyncMirrorRules: []*s3.SyncMirrorRules{ { MatchCondition: s3.MatchCondition{ HTTPCodes: []*string{ aws.String("404"), }, KeyPrefixes: []*string{ aws.String("abc"), }, }, MirrorURL: aws.String("http://v-ks-a-i.originalvod.com"), MirrorRequestSetting: &s3.MirrorRequestSetting{ PassQueryString: aws.Boolean(true), Follow3Xx: aws.Boolean(true), HeaderSetting: &s3.HeaderSetting{ SetHeaders: []*s3.SetHeaders{ { aws.String("a"), aws.String("b"), }, }, RemoveHeaders: []*s3.RemoveHeaders{ { aws.String("daaaaa"), }, }, PassAll: aws.Boolean(true), //PassHeaders: []*s3.PassHeaders{ // { // aws.String("asdb"), // }, //}, }, }, SavingSetting: &s3.SavingSetting{ ACL: aws.String("private"), }, }, }, }, } resp, err := client.PutBucketMirror(params) if err != nil { if awsErr, ok := err.(awserr.Error); ok { // Generic AWS Error with Code, Message, and original error (if any) fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) if reqErr, ok := err.(awserr.RequestFailure); ok { // A service error occurred fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { // This case should never be hit, The SDK should alwsy return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } } fmt.Println("resp.code is:", resp.HttpCode) fmt.Println("resp.Header is:", resp.Header) // Pretty-print the response data. var bodyStr = string(resp.Body[:]) fmt.Println("resp.Body is:", bodyStr) } ``` -------------------------------- ### Initialize Multipart Upload with KS3 Go SDK Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Initiates a multipart upload for a large object. This step is required before uploading individual parts and returns an UploadID. ```go params := &s3.CreateMultipartUploadInput{ Bucket: aws.String("BucketName"), // bucket名称 Key: aws.String("ObjectKey"), // object key ACL: aws.String("ObjectCannedACL"),//权限,支持private(私有),public-read(公开读) ContentType: aws.String("application/octet-stream"),//设置content-type Metadata: map[string]*string{ //"Key": aws.String("MetadataValue"), // 设置用户元数据 // More values... }, } resp, err := client.CreateMultipartUpload(params) if err != nil{ panic(err) } //获取这次初始化的uploadid fmt.Println(*resp.UploadID) ``` -------------------------------- ### List Uploaded Parts for Multipart Upload with KS3 Go SDK Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Lists all the parts that have been uploaded for a specific multipart upload. Requires bucket name, object key, and upload ID. ```go params := &s3.ListPartsInput{ Bucket:aws.String(bucket),//bucket名称 Key:aws.String(key),//文件名 UploadID:aws.String(uploadId),//由初始化获取到得uploadid } resp,err := client.ListParts(params) if err != nil{ panic(err) } fmt.Println(resp) ``` -------------------------------- ### List Files in Bucket Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Lists objects within a bucket, optionally filtered by a prefix and limited by MaxKeys. The `Marker` parameter can be used to paginate results. ```go /** 列举文件 */ func ListObjects() { resp, err := client.ListObjects(&s3.ListObjectsInput{ Bucket: aws.String(BucketName), Prefix: aws.String("onlineTask/"), //文件前缀 // Marker: aws.String("Marker"), //从按个key开始获取 MaxKeys: aws.Long(1000), //最大数量 }) if err != nil { fmt.Println(resp) } fmt.Println(len(resp.Contents)) } ``` -------------------------------- ### Copy Object with KS3 Go SDK Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Demonstrates how to copy an object from one location to another within KS3 using the SDK. Includes error handling for AWS SDK errors. ```go func CopyObject() { input := s3.CopyObjectInput{ Bucket: aws.String(bucketname), Key: aws.String(key), CopySource: aws.String("/cqc-test-b/yztestfile1"), } resp, err := svc.CopyObject(&input) if err != nil { if awsErr, ok := err.(awserr.Error); ok { fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) if reqErr, ok := err.(awserr.RequestFailure); ok { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { fmt.Println(err.Error()) } } fmt.Println("结果:\n", awsutil.StringValue(resp)) } ``` -------------------------------- ### Upload File with KS3 Go SDK Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Uploads a local file to a specified bucket and key. Allows setting ACL, content type, and user-defined metadata. Handles file reading and error checking. ```go func putFile(filename string) { if len(filename) == 0 { filename = "/Users/user/Downloads/aaa.docx" } file, err := ioutil.ReadFile(filename) if err != nil { fmt.Println("Failed to open file", err) os.Exit(1) } params := &s3.PutObjectInput{ Bucket: aws.String(BucketName), // bucket名称 Key: aws.String("go-demo/test"), // object key ACL: aws.String("public-read"), //权限,支持private(私有),public-read(公开读) Body: bytes.NewReader(file), //要上传的内容 ContentType: aws.String("application/octet-stream"), //设置content-type Metadata: map[string]*string{ //"Key": aws.String("MetadataValue"), // 设置用户元数据 // More values... }, } resp, err := client.PutObject(params) if err != nil { panic(err) } fmt.Println(resp) //获取新的文件名 fmt.Println(*resp) } ``` -------------------------------- ### Create Multipart Upload Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Initializes a multipart upload for an object. This is the first step in uploading an object in parts. ```APIDOC ## CreateMultipartUpload ### Description Initializes a multipart upload for an object. ### Method params := &s3.CreateMultipartUploadInput{ Bucket: aws.String("BucketName"), // bucket名称 Key: aws.String("ObjectKey"), // object key ACL: aws.String("ObjectCannedACL"),//权限,支持private(私有),public-read(公开读) ContentType: aws.String("application/octet-stream"),//设置content-type Metadata: map[string]*string{ //"Key": aws.String("MetadataValue"), // 设置用户元数据 // More values... }, } resp, err := client.CreateMultipartUpload(params) if err != nil{ panic(err) } //获取这次初始化的uploadid fmt.Println(*resp.UploadID) ### Parameters - Bucket (string) - Required - The bucket name. - Key (string) - Required - The object key. - ACL (string) - Optional - The canned ACL to apply to the object (e.g., "private", "public-read"). - ContentType (string) - Optional - The content type of the object. - Metadata (map[string]*string) - Optional - User-defined metadata for the object. ``` -------------------------------- ### Generate Token for Mobile (Go) Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 This snippet demonstrates how to generate a token for mobile clients using HMAC-SHA1 and Base64 encoding. Ensure you have the necessary keys and string to sign. ```Go package main import( "crypto/hmac" "crypto/sha1" "encoding/base64" "fmt" ) func main(){ AccessKeyId := "AccessKeyId" AccessKeySecret:= "AccessKeySecret" stringToSign := "stringToSign" signature := string(base64Encode(makeHmac([]byte(AccessKeySecret), []byte(stringToSign)))) token := "KSS "+AccessKeyId+":"+signature fmt.Println(token) } func makeHmac(key []byte, data []byte) []byte { hash := hmac.New(sha1.New, key) hash.Write(data) return hash.Sum(nil) } func base64Encode(src []byte) []byte { return []byte(base64.StdEncoding.EncodeToString(src)) } ``` -------------------------------- ### Set Object Tags with KS3 Go SDK Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Shows how to set tags for an object in KS3. This involves creating a Tagging structure with key-value pairs and passing it to the PutObjectTaggingInput. ```go func PutObjectTag() { tagkey := "name" tagval := "yz" tagkey2 := "sex" tagval2 := "female" objTagging := s3.Tagging{ TagSet: []*s3.Tag{&s3.Tag{ Key: aws.String(tagkey), Value: aws.String(tagval), }, &s3.Tag{ Key: aws.String(tagkey2), Value: aws.String(tagval2), }, }, } params := &s3.PutObjectTaggingInput{ Bucket: aws.String(bucketname), // Required Key: aws.String(key), Tagging: &objTagging, } resp, err := client.PutObjectTagging(params) if err != nil { if awsErr, ok := err.(awserr.Error); ok { fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) if reqErr, ok := err.(awserr.RequestFailure); ok { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { fmt.Println(err.Error()) } } fmt.Println("结果:\n", awsutil.StringValue(resp)) } ``` -------------------------------- ### Generate File Download Presigned URL Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Generates a presigned URL for downloading a file. The second parameter specifies the expiration time in nanoseconds. ```go params := &s3.GetObjectInput{ Bucket: aws.String("BucketName"), // bucket名称 Key: aws.String("ObjectKey"), // object key ResponseCacheControl: aws.String("ResponseCacheControl"), //控制返回的Cache-Control header ResponseContentDisposition: aws.String("ResponseContentDisposition"), //控制返回的Content-Disposition header ResponseContentEncoding: aws.String("ResponseContentEncoding"), //控制返回的Content-Encoding header ResponseContentLanguage: aws.String("ResponseContentLanguage"), //控制返回的Content-Language header ResponseContentType: aws.String("ResponseContentType"), //控制返回的Content-Type header } resp, err := client.GetObjectPresignedUrl(params,1444370289000000000) //第二个参数为外链过期时间,为纳秒级的时间戳 if err!=nil { panic(err) } fmt.Println(resp)//resp即生成的外链地址,类型为url.URL ``` -------------------------------- ### List Parts Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Lists all the parts that have been uploaded for a specific multipart upload. ```APIDOC ## ListParts ### Description Lists all parts uploaded for a specific multipart upload. ### Method params := &s3.ListPartsInput{ Bucket:aws.String(bucket),//bucket名称 Key:aws.String(key),//文件名 UploadID:aws.String(uploadId),//由初始化获取到得uploadid } resp,err := client.ListParts(params) if err != nil{ panic(err) } fmt.Println(resp) ### Parameters - Bucket (string) - Required - The bucket name. - Key (string) - Required - The object key. - UploadID (string) - Required - The ID of the multipart upload. ``` -------------------------------- ### Generate Presigned URL for Setting Object ACL Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Generates a presigned URL to set the ACL for an object. The expiration time is provided in nanoseconds. ```go params := &s3.PutObjectACLInput{ Bucket: aws.String(bucket), // bucket名称 Key: aws.String(key), // object key ACL: aws.String("private"),//设置ACL ContentType: aws.String("text/plain"), } resp, err := client.PutObjectACLPresignedUrl(params,1444370289000000000) //第二个参数为外链过期时间,为纳秒级的时间戳 if err!=nil { panic(err) } fmt.Println(resp)//resp即生成的外链地址,类型为url.URL httpReq, _ := http.NewRequest("PUT", "", nil) httpReq.URL = resp httpReq.Header["x-amz-acl"] = []string{"private"} httpReq.Header.Add("Content-Type","text/plain") fmt.Println(httpReq) httpRep,err := http.DefaultClient.Do(httpReq) if err != nil{ panic(err) } fmt.Println(httpRep) ``` -------------------------------- ### GetBucketMirrorRules Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Retrieves the mirror rules configuration for a specified bucket. ```APIDOC ## GetBucketMirrorRules ### Description Retrieves the mirror rules configuration for a specified bucket. ### Method client.GetBucketMirror ### Parameters #### Request Body - **Bucket** (string) - Required - The name of the bucket. ### Response Example ```json { "HttpCode": 200, "Header": {}, "Body": "{...}" } ``` ``` -------------------------------- ### Generate File Upload Presigned URL Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Generates a presigned URL for uploading a file. This includes setting ACL, ContentType, and ContentMaxLength. The second parameter is the expiration time in nanoseconds. ```go params := &s3.PutObjectInput{ Bucket: aws.String(bucket), // bucket名称 Key: aws.String(key), // object key ACL: aws.String("public-read"),//设置ACL ContentType: aws.String("application/octet-stream"),//设置文件的content-type ContentMaxLength: aws.Long(20),//设置允许的最大长度,对应的header:x-amz-content-maxlength } resp, err := client.PutObjectPresignedUrl(params,1444370289000000000) //第二个参数为外链过期时间,为纳秒级的时间戳 if err!=nil { panic(err) } httpReq, _ := http.NewRequest("PUT", "", strings.NewReader("123")) httpReq.URL = resp httpReq.Header["x-amz-acl"] = []string{"public-read"} httpReq.Header["x-amz-content-maxlength"] = []string{"20"} httpReq.Header.Add("Content-Type","application/octet-stream") fmt.Println(httpReq) httpRep,err := http.DefaultClient.Do(httpReq) fmt.Println(httpRep) if err != nil{ panic(err) } ``` -------------------------------- ### GetObject Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Downloads an object from a bucket. Allows reading a portion of the object's body. ```APIDOC ## GetObject ### Description Downloads an object from a bucket. Allows reading a portion of the object's body. ### Method client.GetObject ### Parameters #### Request Body - **Bucket** (string) - Required - The name of the bucket. - **Key** (string) - Required - The key of the object. ### Response Example ```json { "Body": "{...}" } ``` ``` -------------------------------- ### Delete Directory (Prefix) Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Deletes objects within a specified prefix (directory) in a bucket. The `Prefix` parameter defines the directory to be deleted. ```go func DeleteBucketPrefix(prefix string) { params := &s3.DeleteBucketPrefixInput{ Bucket: aws.String(""), //桶名称 Prefix: aws.String(prefix), //前缀(目录)名称 } resp, _ := svc.DeleteBucketPrefix(params) //执行并接受响应结果 fmt.Println("error keys:",resp.Errors) fmt.Println("deleted keys:",resp.Deleted) } ``` -------------------------------- ### PutBucketMirrorRules Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Sets or updates the mirror rules for a specified bucket. This includes configuring both asynchronous and synchronous mirror rules with various settings like mirror URLs, request conditions, and saving configurations. ```APIDOC ## PutBucketMirrorRules ### Description Sets or updates the mirror rules for a specified bucket. This includes configuring both asynchronous and synchronous mirror rules with various settings like mirror URLs, request conditions, and saving configurations. ### Method client.PutBucketMirror ### Parameters #### Request Body - **Bucket** (string) - Required - The name of the bucket. - **BucketMirror** (object) - Required - Configuration for bucket mirroring. - **Version** (string) - Required - The version of the mirror rule. - **UseDefaultRobots** (boolean) - Required - Whether to use the default robots.txt. - **AsyncMirrorRule** (object) - Optional - Configuration for asynchronous mirror rules. - **MirrorUrls** ([]string) - Required - List of mirror URLs for asynchronous mirroring. - **SavingSetting** (object) - Optional - Saving settings for asynchronous mirroring. - **ACL** (string) - Optional - The ACL setting for saved objects. - **SyncMirrorRules** ([]object) - Optional - List of synchronous mirror rules. - **MatchCondition** (object) - Required - Conditions to trigger synchronous mirroring. - **HTTPCodes** ([]string) - Optional - List of HTTP status codes that trigger mirroring. - **KeyPrefixes** ([]string) - Optional - List of key prefixes that trigger mirroring. - **MirrorURL** (string) - Required - The mirror URL for synchronous mirroring. - **MirrorRequestSetting** (object) - Optional - Settings for mirror requests. - **PassQueryString** (boolean) - Optional - Whether to pass the query string. - **Follow3Xx** (boolean) - Optional - Whether to follow 3xx redirects. - **HeaderSetting** (object) - Optional - Header configuration for mirror requests. - **SetHeaders** ([]object) - Optional - Headers to set in the mirror request. - **RemoveHeaders** ([]object) - Optional - Headers to remove from the mirror request. - **PassAll** (boolean) - Optional - Whether to pass all headers. - **PassHeaders** ([]object) - Optional - Specific headers to pass. - **SavingSetting** (object) - Optional - Saving settings for synchronous mirroring. - **ACL** (string) - Optional - The ACL setting for saved objects. ### Response Example ```json { "HttpCode": 200, "Header": {}, "Body": "{...}" } ``` ``` -------------------------------- ### Upload Part for Multipart Upload with KS3 Go SDK Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Uploads a single part of a multipart upload. Requires the bucket name, object key, part number, upload ID, and the content of the part. ```go params := &s3.UploadPartInput{ Bucket:aws.String(bucket),//bucket名称 Key:aws.String(key),//文件名 PartNumber:aws.Long(1),//当前块的序号 UploadID:aws.String(uploadId),//由初始化获取到得uploadid Body:strings.NewReader(content),//当前块的内容 ContentLength:aws.Long(int64(len(content))),//内容长度 } resp,err := client.UploadPart(params) if err != nil{ panic(err) } fmt.Println(resp) ``` -------------------------------- ### Copy Object Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Copies an object from one location to another within KS3. It requires specifying the source object's bucket and key, as well as the destination bucket and key. ```APIDOC ## CopyObject ### Description Copies an object from one location to another within KS3. ### Method func CopyObject() { input := s3.CopyObjectInput{ Bucket: aws.String(bucketname), Key: aws.String(key), CopySource: aws.String("/cqc-test-b/yztestfile1"), } resp, err := svc.CopyObject(&input) if err != nil { if awsErr, ok := err.(awserr.Error); ok { fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) if reqErr, ok := err.(awserr.RequestFailure); ok { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { fmt.Println(err.Error()) } } fmt.Println("结果:\n", awsutil.StringValue(resp)) } ### Parameters - Bucket (string) - Required - The destination bucket name. - Key (string) - Required - The destination object key. - CopySource (string) - Required - The source object's bucket and key in the format "/bucket/key". ``` -------------------------------- ### Complete Multipart Upload with KS3 Go SDK Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Finalizes a multipart upload by merging all uploaded parts. Requires the bucket name, object key, upload ID, and a list of completed parts. ```go params := &s3.CompleteMultipartUploadInput{ Bucket:aws.String(bucket),//bucket名称 Key:aws.String(key),//文件名 UploadID:aws.String(uploadId),//由初始化获取到得uploadid MultipartUpload:&s3.CompletedMultipartUpload{ Parts:<已经完成的块列表>,//类型为*s3.CompletedPart数组 }, } resp,err := client.CompleteMultipartUpload(params) if err != nil{ panic(err) } fmt.Println(resp) ``` -------------------------------- ### Put Object Tagging Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Sets tags for an object in KS3. Tags are key-value pairs that can be used for organizing and managing objects. ```APIDOC ## PutObjectTag ### Description Sets tags for an object in KS3. ### Method func PutObjectTag() { tagkey := "name" tagval := "yz" tagkey2 := "sex" tagval2 := "female" objTagging := s3.Tagging{ TagSet: []*s3.Tag{&s3.Tag{ Key: aws.String(tagkey), Value: aws.String(tagval), }, &s3.Tag{ Key: aws.String(tagkey2), Value: aws.String(tagval2), }, }, } params := &s3.PutObjectTaggingInput{ Bucket: aws.String(bucketname), // Required Key: aws.String(key), Tagging: &objTagging, } resp, err := client.PutObjectTagging(params) if err != nil { if awsErr, ok := err.(awserr.Error); ok { fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) if reqErr, ok := err.(awserr.RequestFailure); ok { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { fmt.Println(err.Error()) } } fmt.Println("结果:\n", awsutil.StringValue(resp)) } ### Parameters - Bucket (string) - Required - The bucket name. - Key (string) - Required - The object key. - Tagging (*s3.Tagging) - Required - The object's tags. ``` -------------------------------- ### Fetch Remote Data to KS3 Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Fetches data from a remote URL and stores it in KS3. This function includes detailed error handling for AWS errors. ```go func FetchObcjet() { sourceUrl := "https://img0.pconline.com.cn/pconline/1111/04/2483449_20061139501.jpg" input := s3.FetchObjectInput{ Bucket: aws.String(bucketname), Key: aws.String("dst/testa"), SourceUrl: aws.String(sourceUrl), ACL: aws.String("public-read"), } resp, err := svc.FetchObject(&input) if err != nil { if awsErr, ok := err.(awserr.Error); ok { fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) if reqErr, ok := err.(awserr.RequestFailure); ok { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { fmt.Println(err.Error()) } } fmt.Println("结果:\n", awsutil.StringValue(resp)) } } ``` -------------------------------- ### HeadObject Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Retrieves metadata about an object without returning the object itself. Useful for checking object existence and properties. ```APIDOC ## HeadObject ### Description Retrieves metadata about an object without returning the object itself. Useful for checking object existence and properties. ### Method client.HeadObject ### Parameters #### Request Body - **Bucket** (string) - Required - The name of the bucket. - **Key** (string) - Required - The key of the object. ### Response Example ```json { "Result": "{...}" } ``` ``` -------------------------------- ### Delete Bucket Mirror Rules with KS3 Go SDK Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Removes all configured mirror source rules from a specified bucket. Use this when mirror functionality is no longer needed. ```go //删除镜像回源规则 func DeleteBucketMirrorRules() { params := &s3.DeleteBucketMirrorInput{ Bucket: aws.String(BucketName), } resp, _ := client.DeleteBucketMirror(params) fmt.Println("resp.code is:", resp.HttpCode) fmt.Println("resp.Header is:", resp.Header) // Pretty-print the response data. var bodyStr = string(resp.Body[:]) fmt.Println("resp.Body is:", bodyStr) } ``` -------------------------------- ### PutObject Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Uploads a new object or overwrites an existing object in a bucket. Supports setting ACL, content type, and user-defined metadata. ```APIDOC ## PutObject ### Description Uploads a new object or overwrites an existing object in a bucket. Supports setting ACL, content type, and user-defined metadata. ### Method client.PutObject ### Parameters #### Request Body - **Bucket** (string) - Required - The name of the bucket. - **Key** (string) - Required - The key of the object. - **ACL** (string) - Optional - The ACL permission for the object (e.g., "private", "public-read"). - **Body** (bytes) - Required - The content of the object to upload. - **ContentType** (string) - Optional - The content type of the object (e.g., "application/octet-stream"). - **Metadata** (map[string]string) - Optional - User-defined metadata for the object. ### Response Example ```json { "resp": "{...}" } ``` ``` -------------------------------- ### Batch Delete Objects Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Deletes multiple objects from a bucket in a single operation. The `Delete` field requires a list of `ObjectIdentifier`s. ```go func DeleteObjects() { params := &s3.DeleteObjectsInput{ Bucket: aws.String(""), // 桶名称 Delete: &s3.Delete{ // Delete Required Objects: []*s3.ObjectIdentifier{ { Key: aws.String("1"), // 目标对象1的key }, { Key: aws.String("2"), // 目标对象2的key }, // More values... }, }, } resp := svc.DeleteObjects(params) //执行并返回响应结果 fmt.Println("error keys:",resp.Errors) fmt.Println("deleted keys:",resp.Deleted) } ``` -------------------------------- ### Upload Part Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Uploads a single part of a multipart upload. Each part must be uploaded before completing the multipart upload. ```APIDOC ## UploadPart ### Description Uploads a single part of a multipart upload. ### Method params := &s3.UploadPartInput{ Bucket:aws.String(bucket),//bucket名称 Key:aws.String(key),//文件名 PartNumber:aws.Long(1),//当前块的序号 UploadID:aws.String(uploadId),//由初始化获取到得uploadid Body:strings.NewReader(content),//当前块的内容 ContentLength:aws.Long(int64(len(content))),//内容长度 } resp,err := client.UploadPart(params) if err != nil{ panic(err) } fmt.Println(resp) ### Parameters - Bucket (string) - Required - The bucket name. - Key (string) - Required - The object key. - PartNumber (int64) - Required - The sequential number of the part being uploaded. - UploadID (string) - Required - The ID of the multipart upload. - Body (io.Reader) - Required - The content of the part. - ContentLength (int64) - Required - The length of the part content. ``` -------------------------------- ### Complete Multipart Upload Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Completes a multipart upload by concatenating all uploaded parts into a single object. ```APIDOC ## CompleteMultipartUpload ### Description Completes a multipart upload by concatenating all uploaded parts. ### Method params := &s3.CompleteMultipartUploadInput{ Bucket:aws.String(bucket),//bucket名称 Key:aws.String(key),//文件名 UploadID:aws.String(uploadId),//由初始化获取到得uploadid MultipartUpload:&s3.CompletedMultipartUpload{ Parts:<已经完成的块列表>,//类型为*s3.CompletedPart数组 }, } resp,err := client.CompleteMultipartUpload(params) if err != nil{ panic(err) } fmt.Println(resp) ### Parameters - Bucket (string) - Required - The bucket name. - Key (string) - Required - The object key. - UploadID (string) - Required - The ID of the multipart upload. - MultipartUpload (*s3.CompletedMultipartUpload) - Required - A list of completed parts. ``` -------------------------------- ### Abort Multipart Upload with KS3 Go SDK Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Cancels an ongoing multipart upload. This is useful if the upload needs to be stopped before completion. ```go params := &s3.AbortMultipartUploadInput{ Bucket:aws.String(bucket),//bucket名称 Key:aws.String(key),//文件名 UploadID:aws.String(uploadId),//由初始化获取到得uploadid } resp,err := client.AbortMultipartUpload(params) if err != nil{ panic(err) } fmt.Println(resp) ``` -------------------------------- ### Delete Object Tags with KS3 Go SDK Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Removes all tags from a specified object in KS3. This operation requires the bucket name and object key. ```go func DeleteObjectTag() { params := &s3.DeleteObjectTaggingInput{ Bucket: aws.String(bucketname), // Required Key: aws.String(key), } resp, err := client.DeleteObjectTagging(params) if err != nil { if awsErr, ok := err.(awserr.Error); ok { fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) if reqErr, ok := err.(awserr.RequestFailure); ok { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { fmt.Println(err.Error()) } } fmt.Println("结果:\n", awsutil.StringValue(resp)) } ``` -------------------------------- ### DeleteBucketMirrorRules Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Deletes the mirror rules configuration for a specified bucket. ```APIDOC ## DeleteBucketMirrorRules ### Description Deletes the mirror rules configuration for a specified bucket. ### Method client.DeleteBucketMirror ### Parameters #### Request Body - **Bucket** (string) - Required - The name of the bucket. ### Response Example ```json { "HttpCode": 200, "Header": {}, "Body": "{...}" } ``` ``` -------------------------------- ### Abort Multipart Upload Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Aborts a multipart upload. This operation is used to clean up any parts that may have been uploaded. ```APIDOC ## AbortMultipartUpload ### Description Aborts a multipart upload. ### Method params := &s3.AbortMultipartUploadInput{ Bucket:aws.String(bucket),//bucket名称 Key:aws.String(key),//文件名 UploadID:aws.String(uploadId),//由初始化获取到得uploadid } resp,err := client.AbortMultipartUpload(params) if err != nil{ panic(err) } fmt.Println(resp) ### Parameters - Bucket (string) - Required - The bucket name. - Key (string) - Required - The object key. - UploadID (string) - Required - The ID of the multipart upload to abort. ``` -------------------------------- ### Modify Object Metadata Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Modifies the metadata of an object using a CopyObject operation with MetadataDirective set to REPLACE. ```go func TestModifyObjectMeta(t *testing.T) { key_modify_meta := string("yourkey") metadata := make(map[string]*string) metadata["yourmetakey1"] = aws.String("yourmetavalue1") metadata["yourmetakey2"] = aws.String("yourmetavalue2") _,err := svc.CopyObject(&s3.CopyObjectInput{ Bucket:aws.String(bucket), Key:aws.String(key_modify_meta), CopySource:aws.String("/ ``` -------------------------------- ### Delete Object Tagging Source: https://github.com/ks3sdklib/aws-sdk-go/wiki/KS3-Go-SDK-使用指南 Deletes all tags associated with an object in KS3. ```APIDOC ## DeleteObjectTag ### Description Deletes all tags associated with an object in KS3. ### Method func DeleteObjectTag() { params := &s3.DeleteObjectTaggingInput{ Bucket: aws.String(bucketname), // Required Key: aws.String(key), } resp, err := client.DeleteObjectTagging(params) if err != nil { if awsErr, ok := err.(awserr.Error); ok { fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) if reqErr, ok := err.(awserr.RequestFailure); ok { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { fmt.Println(err.Error()) } } fmt.Println("结果:\n", awsutil.StringValue(resp)) } ### Parameters - Bucket (string) - Required - The bucket name. - Key (string) - Required - The object key. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.