### Starting an HTTP Server Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Examples of setting up HTTP handlers and starting a server. ```go http.Handle("/foo", fooHandler) http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) }) log.Fatal(http.ListenAndServe(":8080", nil)) ``` ```go s := &http.Server{ Addr: ":8080", Handler: myHandler, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } log.Fatal(s.ListenAndServe()) ``` -------------------------------- ### GetBucketCORS Usage Example Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-client.md Example demonstrating how to retrieve and iterate over CORS rules for a bucket. ```go result, err := client.GetBucketCORS("my-bucket") if err != nil { log.Fatal(err) } for _, rule := range result.CORSRules { fmt.Println("Origins:", rule.AllowedOrigin) } ``` -------------------------------- ### Hello World in Go Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html A basic example of a Go program printing to the console. ```go package main import "fmt" func main() { fmt.Println("Hello, 世界") } ``` -------------------------------- ### Serve Static Files with FileServer Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Examples demonstrating how to serve static files using http.FileServer. ```go http.Handle("/", http.FileServer(http.Dir("/tmp"))) ``` ```go package main import ( "log" "net/http" ) func main() { // Simple static webserver: log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc")))) } ``` ```go package main import ( "net/http" ) func main() { // To serve a directory on disk (/tmp) under an alternate URL // path (/tmpfiles/), use StripPrefix to modify the request // URL's path before the FileServer sees it: http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp")))) } ``` -------------------------------- ### SetBucketCORS Usage Example Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-client.md Example demonstrating how to define CORS rules and apply them to a specific bucket. ```go rules := []oss.CORSRule{ { AllowedOrigin: []string{"*"}, AllowedMethod: []string{"GET", "POST"}, AllowedHeader: []string{"*"}, ExposeHeader: []string{"ETag"}, MaxAgeSeconds: 3600, }, } err := client.SetBucketCORS("my-bucket", rules) if err != nil { log.Fatal(err) } ``` -------------------------------- ### ListenAndServe Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Starts an HTTP server on a specified address. ```APIDOC ## func ListenAndServe(addr string, handler Handler) error ### Description Listens on the TCP network address addr and then calls Serve with handler to handle requests on incoming connections. ### Parameters - **addr** (string) - Required - The TCP address to listen on. - **handler** (Handler) - Optional - The handler to use; if nil, DefaultServeMux is used. ``` -------------------------------- ### Create an HTTPS Server Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Starts an HTTPS server requiring certificate and key files for secure communication. ```go import ( "log" "net/http" ) func handler(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "text/plain") w.Write([]byte("This is an example server.\n")) } func main() { http.HandleFunc("/", handler) log.Printf("About to listen on 10443. Go to https://127.0.0.1:10443/") err := http.ListenAndServeTLS(":10443", "cert.pem", "key.pem", nil) if err != nil { log.Fatal(err) } } ``` -------------------------------- ### http.ListenAndServe Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Starts an HTTP server with a given address and handler. ```APIDOC ## func ListenAndServe(addr string, handler Handler) error ### Description ListenAndServe listens on the TCP network address addr and then calls Serve with handler to handle requests on incoming connections. ### Parameters - **addr** (string) - Required - The TCP address to listen on. - **handler** (Handler) - Required - The handler to invoke, or nil to use DefaultServeMux. ``` -------------------------------- ### Implement Custom Credentials Provider Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/configuration.md Example implementation of the CredentialsProvider interface for manual credential management. ```go type MyCredentialsProvider struct{} func (p *MyCredentialsProvider) GetCredentials() oss.Credentials { return &MyCredentials{ AccessKeyID: "your-key-id", AccessKeySecret: "your-key-secret", SecurityToken: "", } } type MyCredentials struct { AccessKeyID string AccessKeySecret string SecurityToken string } func (c *MyCredentials) GetAccessKeyID() string { return c.AccessKeyID } func (c *MyCredentials) GetAccessKeySecret() string { return c.AccessKeySecret } func (c *MyCredentials) GetSecurityToken() string { return c.SecurityToken } ``` -------------------------------- ### Perform an HTTP GET request Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Example of using http.Get to fetch a resource and read the response body. Ensure the response body is closed after reading to prevent resource leaks. ```go package main import ( "fmt" "io/ioutil" "log" "net/http" ) func main() { res, err := http.Get("http://www.google.com/robots.txt") if err != nil { log.Fatal(err) } robots, err := ioutil.ReadAll(res.Body) res.Body.Close() if err != nil { log.Fatal(err) } fmt.Printf("%s", robots) } ``` -------------------------------- ### ListenAndServeTLS Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Starts an HTTPS server on a specified address. ```APIDOC ## func ListenAndServeTLS(addr string, certFile string, keyFile string, handler Handler) error ### Description Acts identically to ListenAndServe, except that it expects HTTPS connections using the provided certificate and private key files. ### Parameters - **addr** (string) - Required - The TCP address to listen on. - **certFile** (string) - Required - Path to the certificate file. - **keyFile** (string) - Required - Path to the private key file. - **handler** (Handler) - Optional - The handler to use. ``` -------------------------------- ### Create a Basic HTTP Server Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Registers a handler function and starts an HTTP server on a specified port. ```go package main import ( "io" "net/http" "log" ) // hello world, the web server func HelloServer(w http.ResponseWriter, req *http.Request) { io.WriteString(w, "hello, world!\n") } func main() { http.HandleFunc("/hello", HelloServer) err := http.ListenAndServe(":12345", nil) if err != nil { log.Fatal("ListenAndServe: ", err) } } ``` -------------------------------- ### Use Marker Option Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-options.md Sets the starting point for pagination in a list operation. ```go result, err := bucket.ListObjects( oss.Marker("file-z"), oss.MaxKeys(50), ) ``` -------------------------------- ### func (*Server) ListenAndServe Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Starts the HTTP server on the configured TCP address. ```APIDOC ## func (*Server) ListenAndServe ### Description Listens on the TCP network address srv.Addr and then calls Serve to handle requests on incoming connections. If srv.Addr is blank, ":http" is used. ### Signature func (srv *Server) ListenAndServe() error ``` -------------------------------- ### Performing HTTP Requests Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Examples of making various types of HTTP requests using the net/http package. ```go resp, err := http.Get("http://example.com/") ``` ```go resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf) ``` ```go resp, err := http.PostForm("http://example.com/form", url.Values{"key": {"Value"}, "id": {"123"}}) ``` -------------------------------- ### func (*Client) Get Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Issues a GET request to the specified URL and follows redirects if necessary. ```APIDOC ## func (*Client) Get(url string) (resp *Response, err error) ### Description Issues a GET request to the specified URL. If the response is a redirect (301, 302, 303, or 307), it follows the redirect after calling the Client's CheckRedirect function. ### Parameters - **url** (string) - Required - The URL to send the GET request to. ### Response - **resp** (*Response) - The HTTP response object. The caller is responsible for closing resp.Body. - **err** (error) - An error object if the request fails or the redirect check fails. ``` -------------------------------- ### GetBucketWebsite Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-client.md Gets the website configuration of a bucket. ```APIDOC ## GetBucketWebsite ### Description Gets the website configuration of a bucket. ### Method func (client Client) GetBucketWebsite(bucketName string, options ...Option) (GetBucketWebsiteResult, error) ### Parameters - **bucketName** (string) - Required - Bucket name - **options** ([]Option) - Optional - Additional request options ### Returns - **GetBucketWebsiteResult** - Website configuration - **error** - Error if request fails ``` -------------------------------- ### func (srv *Server) ListenAndServe() error Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Starts an HTTP server on the address specified in the Server configuration. ```APIDOC ## func (srv *Server) ListenAndServe() ### Description Listens on the TCP network address srv.Addr and then calls Serve with handler to handle requests on incoming connections. ### Response - **error** (error) - Returns an error if the server fails to start or encounters a fatal error. ``` -------------------------------- ### Get Object with Go SDK Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/README.md Downloads an object from the bucket to a local file path. ```go client, err := oss.New("Endpoint", "AccessKeyId", "AccessKeySecret") if err != nil { // HandleError(err) } bucket, err := client.Bucket("my-bucket") if err != nil { // HandleError(err) } err = bucket.GetObjectToFile("my-object", "LocalFile") if err != nil { // HandleError(err) } ``` -------------------------------- ### Get Bucket Lifecycle Configuration Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-client.md Retrieves the current lifecycle configuration rules for a bucket. ```go func (client Client) GetBucketLifecycle(bucketName string, options ...Option) (GetBucketLifecycleResult, error) ``` ```go result, err := client.GetBucketLifecycle("my-bucket") if err != nil { log.Fatal(err) } for _, rule := range result.Rules { fmt.Println("Rule ID:", rule.ID, "Status:", rule.Status) } ``` -------------------------------- ### Client.Get Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Issues a GET request to the specified URL. ```APIDOC ## func (c *Client) Get(url string) (resp *Response, err error) ### Description Issues a GET request to the specified URL. If the response is one of the following redirect codes, Get redirects the request following the redirect headers. ### Parameters - **url** (string) - Required - The URL to fetch. ``` -------------------------------- ### Bucket Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-client.md Gets a bucket instance for performing object operations. ```APIDOC ## func (client Client) Bucket(bucketName string) (*Bucket, error) ### Description Gets a bucket instance for performing object operations. ### Parameters - **bucketName** (string) - Required - Bucket name (3-255 characters, lowercase letters, numbers, hyphens) ### Returns - `*Bucket` - Bucket instance for object operations - `error` - Error if bucket name validation fails ### Example ```go bucket, err := client.Bucket("my-bucket") if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Define HTTP Header Mapping Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Example of how HTTP headers are represented as a map of string slices in Go. ```go Header = map[string][]string{ "Accept-Encoding": {"gzip, deflate"}, "Accept-Language": {"en-us"}, "Connection": {"keep-alive"}, } ``` -------------------------------- ### Marker(value string) Option Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-options.md Sets start marker for pagination. ```APIDOC ## Marker(value string) Option ### Description Sets start marker for pagination. ### Parameters - **value** (string) - Required - Marker key (list starts after this) ### Example ```go result, err := bucket.ListObjects( oss.Marker("file-z"), oss.MaxKeys(50), ) ``` ``` -------------------------------- ### Download object with signed URL Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-bucket.md Downloads an object using a pre-signed URL with the HTTP GET method. Ensure the returned reader is closed after use. ```go func (bucket Bucket) GetObjectWithURL(signedURL string, options ...Option) (io.ReadCloser, error) ``` ```go url, _ := bucket.SignURL("myobject.txt", oss.HTTPGet, 3600) reader, err := bucket.GetObjectWithURL(url) if err != nil { log.Fatal(err) } defer reader.Close() ``` -------------------------------- ### Common OSS Error Scenarios Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/errors.md Examples of error messages returned by the OSS service for various failure conditions. ```text Error: oss: service returned error: StatusCode=404, ErrorCode=NoSuchBucket, ErrorMessage="The specified bucket does not exist" ``` ```text Error: oss: service returned error: StatusCode=403, ErrorCode=AccessDenied, ErrorMessage="Access Denied" ``` ```text Error: oss: service returned error: StatusCode=408, ErrorCode=RequestTimeout ``` ```text Error: oss: service returned error: StatusCode=403, ErrorCode=SignatureDoesNotMatch ``` ```text Error: oss: service returned error: StatusCode=404, ErrorCode=NoSuchKey, ErrorMessage="The specified key does not exist" ``` -------------------------------- ### Initialize OSS Client with Options Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/configuration.md Use the New function to create a client instance, passing variadic ClientOption functions to configure specific behaviors. ```go client, err := oss.New( endpoint, accessKeyID, accessKeySecret, options..., ) ``` -------------------------------- ### func Get Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Issues a GET request to the specified URL, following up to 10 redirects. ```APIDOC ## func Get(url string) (*Response, error) ### Description Get issues a GET to the specified URL. If the response is one of the redirect codes (301, 302, 303, 307), Get follows the redirect, up to a maximum of 10 redirects. ### Parameters - **url** (string) - Required - The URL to request. ### Response - **resp** (*Response) - The HTTP response object. - **err** (error) - An error if the request failed or too many redirects occurred. ``` -------------------------------- ### Initialize OSS Client with Options Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/README.md Configure the OSS client using functional options for logging and log levels. ```go client, err := oss.New( endpoint, accessKeyID, accessKeySecret, oss.SetLogger(logger), oss.SetLogLevel(oss.Info), ) ``` -------------------------------- ### Initialize OSS Client Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/README.md Create a new OSS client instance using your endpoint and credentials. ```go package main import ( "log" "github.com/aliyun/aliyun-oss-go-sdk/oss" ) func main() { client, err := oss.New( "http://oss-cn-hangzhou.aliyuncs.com", "your-access-key-id", "your-access-key-secret", ) if err != nil { log.Fatal(err) } // Use client... } ``` -------------------------------- ### Initialize Client with Default Credentials Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/configuration.md Uses explicit parameters to initialize the OSS client. ```go client, err := oss.New( endpoint, accessKeyID, accessKeySecret, ) ``` -------------------------------- ### func Get(url string) (resp *Response, err error) Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Performs an HTTP GET request to the specified URL. ```APIDOC ## func Get(url string) ### Description Issues a GET request to the specified URL. ### Parameters - **url** (string) - Required - The URL to fetch. ### Response - **resp** (*Response) - The HTTP response. - **err** (error) - Error encountered during the request. ``` -------------------------------- ### Use Environment Variable Credentials Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/configuration.md Initialize an OSS client using credentials sourced from environment variables. ```go // Create provider from environment variables provider, err := oss.NewEnvironmentVariableCredentialsProvider() if err != nil { log.Fatal(err) } // Create client with provider config := &oss.Config{ Endpoint: "http://oss-cn-hangzhou.aliyuncs.com", CredentialsProvider: provider, } ``` -------------------------------- ### Client Initialization Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt Methods for creating and configuring the OSS client instance. ```APIDOC ## New(endpoint, accessKeyID, accessKeySecret, options...) ### Description Creates a new OSS client instance to interact with the Aliyun OSS service. ### Parameters - **endpoint** (string) - Required - The OSS service endpoint. - **accessKeyID** (string) - Required - Your Aliyun Access Key ID. - **accessKeySecret** (string) - Required - Your Aliyun Access Key Secret. - **options** (...ClientOption) - Optional - Additional configuration options. ``` -------------------------------- ### http.Get Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Performs an HTTP GET request to the specified URL. ```APIDOC ## func Get(url string) (resp *Response, err error) ### Description Get issues a GET request to the specified URL. If the response is one of the following redirect codes, Get follows the redirect after calling the CheckRedirect function. ### Parameters - **url** (string) - Required - The URL to fetch. ``` -------------------------------- ### oss.New() Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/configuration.md Initializes a new OSS client with the specified endpoint and credentials, supporting various configuration options. ```APIDOC ## oss.New(endpoint, accessKeyID, accessKeySecret, options...) ### Description Creates a new OSS client instance. You can pass variadic `ClientOption` functions to customize the client's behavior. ### Parameters - **endpoint** (string) - Required - The OSS endpoint URL. - **accessKeyID** (string) - Required - The Access Key ID for authentication. - **accessKeySecret** (string) - Required - The Access Key Secret for authentication. - **options** (...ClientOption) - Optional - A list of configuration options to customize the client. ### Available Client Options - **UseCname(bool)** - Use CNAME endpoint instead of domain. - **Timeout(time.Duration)** - Request timeout (default: 60s). - **SecurityToken(string)** - STS security token for temporary credentials. - **UserAgent(string)** - Custom user agent string. - **ProxyHost(string)** - HTTP proxy host. - **ProxyUser(string) / ProxyPassword(string)** - Proxy authentication credentials. - **EnablePathStyle(bool)** - Use path-style URLs. - **AuthVersion(string)** - Authentication signature version: "v1", "v2", or "v4". - **HTTPClient(*http.Client)** - Custom HTTP client. - **SetHTTPTimeout(HTTPTimeout)** - Custom HTTP timeout settings. - **SetHTTPMaxConns(HTTPMaxConns)** - HTTP connection pool limits. - **SetCredentialsProvider(CredentialsProvider)** - Custom credentials provider. - **EnableCRC(bool)** - Enable CRC64 verification (default: true). - **EnableMD5(bool)** - Enable MD5 verification (default: false). - **SetLogger(*log.Logger)** - Custom logger. - **SetLogLevel(int)** - Logging level (LogOff, Error, Warn, Info, Debug). - **LimitUploadSpeed(int)** - Upload speed limit in KB/s. - **LimitDownloadSpeed(int)** - Download speed limit in KB/s. ``` -------------------------------- ### Initialize Environment Variable Provider Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/configuration.md Loads credentials from OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and optionally OSS_SESSION_TOKEN environment variables. ```go provider, err := oss.NewEnvironmentVariableCredentialsProvider() if err != nil { log.Fatal(err) } ``` -------------------------------- ### Configure bucket static website hosting Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-client.md Sets the index and error documents for static website hosting on a bucket. ```go func (client Client) SetBucketWebsite(bucketName, indexDocument, errorDocument string, options ...Option) error ``` ```go err := client.SetBucketWebsite("my-bucket", "index.html", "error.html") if err != nil { log.Fatal(err) } ``` -------------------------------- ### Configure SDK Logging Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/configuration.md Initialize a logger and apply it to the OSS client with a specific log level. ```go logger := log.New(os.Stdout, "[OSS] ", log.LstdFlags) client, err := oss.New( endpoint, accessKeyID, accessKeySecret, oss.SetLogger(logger), oss.SetLogLevel(oss.Info), ) ``` -------------------------------- ### Create a new OSS bucket Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-client.md Initializes a new bucket with specified access control settings. Requires a valid bucket name and optional configuration parameters. ```go func (client Client) CreateBucket(bucketName string, options ...Option) error ``` ```go err := client.CreateBucket("my-bucket", oss.ACL(oss.ACLPrivate)) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Range(start, end int64) Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-options.md Specifies byte range for partial object download. ```APIDOC ## Range(start, end int64) ### Description Specifies byte range for partial object download. ### Parameters - **start** (int64) - Required - Start byte position (inclusive) - **end** (int64) - Required - End byte position (inclusive) ### Example ```go reader, err := bucket.GetObject("largefile", oss.Range(0, 1023), ) ``` ``` -------------------------------- ### Configure ServeMux Handlers Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Demonstrates registering handlers and handle functions to a ServeMux instance. ```go mux := http.NewServeMux() mux.Handle("/api/", apiHandler{}) mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { // The "/" pattern matches everything, so we need to check // that we're at the root here. if req.URL.Path != "/" { http.NotFound(w, req) return } fmt.Fprintf(w, "Welcome to the home page!") }) ``` -------------------------------- ### Get Bucket ACL in Go Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-client.md Retrieves the current ACL configuration and owner information for a bucket. ```go func (client Client) GetBucketACL(bucketName string, options ...Option) (GetBucketACLResult, error) ``` ```go result, err := client.GetBucketACL("my-bucket") if err != nil { log.Fatal(err) } fmt.Println("ACL:", result.ACL) ``` -------------------------------- ### Configure OSS Client in Go Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/configuration.md Initializes an OSS client with custom logging and configures network timeouts, speed limits, and retry settings. ```go package main import ( "log" "os" "time" "github.com/aliyun/aliyun-oss-go-sdk/oss" ) func main() { logger := log.New(os.Stdout, "[OSS] ", log.LstdFlags) client, err := oss.New( "http://oss-cn-hangzhou.aliyuncs.com", "your-access-key-id", "your-access-key-secret", oss.SetLogger(logger), oss.SetLogLevel(oss.Info), ) if err != nil { log.Fatal(err) } // Configure timeouts config := client.GetConfig() config.HTTPTimeout = oss.HTTPTimeout{ ConnectTimeout: 30 * time.Second, ReadWriteTimeout: 60 * time.Second, HeaderTimeout: 60 * time.Second, LongTimeout: 300 * time.Second, IdleConnTimeout: 50 * time.Second, } // Configure limits config.LimitUploadSpeed(512) // 512 KB/s config.LimitDownloadSpeed(1024) // 1 MB/s // Retry configuration config.RetryTimes = 3 // Set region client.SetRegion("cn-hangzhou") // Get bucket bucket, err := client.Bucket("my-bucket") if err != nil { log.Fatal(err) } // Use bucket... _ = bucket } ``` -------------------------------- ### Create Bucket with Go SDK Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/README.md Creates a new bucket with the specified name. ```go client, err := oss.New("Endpoint", "AccessKeyId", "AccessKeySecret") if err != nil { // HandleError(err) } err = client.CreateBucket("my-bucket") if err != nil { // HandleError(err) } ``` -------------------------------- ### Implement HTTP Trailers Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Demonstrates how to declare and set HTTP trailers that are sent after the response body. ```go package main import ( "io" "net/http" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/sendstrailers", func(w http.ResponseWriter, req *http.Request) { // Before any call to WriteHeader or Write, declare // the trailers you will set during the HTTP // response. These three headers are actually sent in // the trailer. w.Header().Set("Trailer", "AtEnd1, AtEnd2") w.Header().Add("Trailer", "AtEnd3") w.Header().Set("Content-Type", "text/plain; charset=utf-8") // normal header w.WriteHeader(http.StatusOK) w.Header().Set("AtEnd1", "value 1") io.WriteString(w, "This HTTP response has both headers before this text and trailers at the end.\n") w.Header().Set("AtEnd2", "value 2") w.Header().Set("AtEnd3", "value 3") // These will appear as trailers. }) } ``` -------------------------------- ### Serve Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Accepts incoming HTTP connections on a listener and handles them. ```APIDOC ## Serve ### Description Accepts incoming HTTP connections on the listener l, creating a new service goroutine for each. The service goroutines read requests and then call handler to reply to them. ### Signature func Serve(l net.Listener, handler Handler) error ``` -------------------------------- ### Retrieve bucket website configuration Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-client.md Fetches the current website configuration, including index and error document settings. ```go func (client Client) GetBucketWebsite(bucketName string, options ...Option) (GetBucketWebsiteResult, error) ``` ```go result, err := client.GetBucketWebsite("my-bucket") if err != nil { log.Fatal(err) } fmt.Println("Index:", result.IndexDocument.Suffix) ``` -------------------------------- ### Get Object ACL in Go Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-bucket.md Retrieves the access control list for a specific object. Requires the object key as a string. ```go func (bucket Bucket) GetObjectACL(objectKey string, options ...Option) (GetObjectACLResult, error) ``` ```go result, err := bucket.GetObjectACL("myobject.txt") if err != nil { log.Fatal(err) } fmt.Println("ACL:", result.ACL) ``` -------------------------------- ### Configure Customer-Provided Encryption (SSE-C) Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-options.md Sets parameters for customer-provided encryption keys, including algorithm, key, and MD5 hash. ```go SSECAlgorithm(value string) Option SSECKey(value string) Option SSECKeyMd5(value string) Option ``` ```go err := bucket.PutObject("file", reader, oss.SSECAlgorithm("AES256"), oss.SSECKey("base64-encoded-key"), oss.SSECKeyMd5("base64-encoded-md5"), ) ``` -------------------------------- ### Specify Byte Range with Range Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-options.md Defines a specific byte range for partial object downloads using start and end positions. ```go Range(start, end int64) Option ``` ```go // Download bytes 0-1023 (first 1KB) reader, err := bucket.GetObject("largefile", oss.Range(0, 1023), ) ``` -------------------------------- ### Execute cross-bucket object copy Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-bucket.md Demonstrates how to copy an object to a different bucket and handle potential errors. ```go result, err := bucket.CopyObjectTo("other-bucket", "dest.txt", "src.txt") if err != nil { log.Fatal(err) } ``` -------------------------------- ### Initialize Bucket Instance Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-client.md Retrieves a bucket instance for performing object operations, returning an error if validation fails. ```go func (client Client) Bucket(bucketName string) (*Bucket, error) ``` ```go bucket, err := client.Bucket("my-bucket") if err != nil { log.Fatal(err) } ``` -------------------------------- ### Configure CNAME and Path-Style URLs Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/configuration.md Enables custom domain names or path-style URL formatting for OSS requests. ```go // Use CNAME client, err := oss.New( "http://my-custom-domain.com", accessKeyID, accessKeySecret, oss.UseCname(true), ) // Use path-style URLs client, err := oss.New( endpoint, accessKeyID, accessKeySecret, oss.EnablePathStyle(true), ) ``` -------------------------------- ### List Buckets with Go SDK Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/README.md Retrieves and prints a list of all buckets associated with the OSS client. ```go client, err := oss.New("Endpoint", "AccessKeyId", "AccessKeySecret") if err != nil { // HandleError(err) } lsRes, err := client.ListBuckets() if err != nil { // HandleError(err) } for _, bucket := range lsRes.Buckets { fmt.Println("Buckets:", bucket.Name) } ``` -------------------------------- ### Set Bandwidth Limits Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/configuration.md Configure upload and download speed limits in KB/s. Setting the value to 0 disables the limit. ```go // Limit upload to 512 KB/s client.GetConfig().LimitUploadSpeed(512) // Limit download to 1024 KB/s client.GetConfig().LimitDownloadSpeed(1024) // Disable limits (0 = unlimited) client.GetConfig().LimitUploadSpeed(0) client.GetConfig().LimitDownloadSpeed(0) ``` -------------------------------- ### Set Client Product Type Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-client.md Specifies the product type, such as oss or oss-cloudbox, for the client. ```go func (client *Client) SetProduct(product string) ``` ```go client.SetProduct("oss") ``` -------------------------------- ### Configuring HTTP Clients Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Customizing HTTP clients for specific needs like redirect policies or custom headers. ```go client := &http.Client{ CheckRedirect: redirectPolicyFunc, } resp, err := client.Get("http://example.com") // ... ``` ```go req, err := http.NewRequest("GET", "http://example.com/", nil) // ... req.Header.Add("If-None-Match", `W/"wyzzy"`) resp, err := client.Do(req) // ... ``` -------------------------------- ### Configure Authentication Version Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/configuration.md Sets the signature version for the OSS client. Use AuthV2 or AuthV4 for specific regions or features. ```go client, err := oss.New( endpoint, accessKeyID, accessKeySecret, oss.AuthVersion(oss.AuthV2), ) ``` -------------------------------- ### Default HTTP Client and ServeMux Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Default instances used for standard HTTP operations. ```go var DefaultClient = &Client{} ``` ```go var DefaultServeMux = NewServeMux() ``` -------------------------------- ### SetBucketWebsite Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-client.md Configures static website hosting for a bucket. ```APIDOC ## SetBucketWebsite ### Description Configures static website hosting for a bucket. ### Method func (client Client) SetBucketWebsite(bucketName, indexDocument, errorDocument string, options ...Option) error ### Parameters - **bucketName** (string) - Required - Bucket name - **indexDocument** (string) - Required - Index document file name (e.g., index.html) - **errorDocument** (string) - Required - 404 error document file name (e.g., error.html) - **options** ([]Option) - Optional - Additional request options ### Returns - **error** - nil on success; error otherwise ``` -------------------------------- ### func (*Server) Serve Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Accepts incoming connections on the Listener l, creating a new service goroutine for each. ```APIDOC ## func (*Server) Serve ### Description Accepts incoming connections on the Listener l, creating a new service goroutine for each. The service goroutines read requests and then call srv.Handler to reply to them. ### Signature `func (srv *Server) Serve(l net.Listener) error` ### Parameters - **l** (net.Listener) - Required - The listener to accept connections from. ``` -------------------------------- ### List Objects Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/README.md List objects in a bucket with optional filtering parameters. ```go result, err := bucket.ListObjects( oss.Prefix("logs/"), oss.Delimiter("/"), oss.MaxKeys(100), ) if err != nil { log.Fatal(err) } for _, obj := range result.Objects { fmt.Println("Object:", obj.Key, "Size:", obj.Size) } ``` -------------------------------- ### List Uploaded Parts in Go Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-multipart.md Lists all parts that have been successfully uploaded for a specific multipart session. ```go func (client Client) ListUploadedParts(bucketName, objectKey, uploadID string, options ...Option) (ListUploadedPartsResult, error) ``` ```go result, err := client.ListUploadedParts("my-bucket", "file", uploadID) if err != nil { log.Fatal(err) } for _, part := range result.Parts { fmt.Printf("Part %d: ETag=%s, Size=%d\n", part.PartNumber, part.ETag, part.Size) } ``` -------------------------------- ### Define Config struct Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/types.md Defines the primary configuration structure for OSS client initialization. ```go type Config struct { Endpoint string AccessKeyID string AccessKeySecret string RetryTimes uint UserAgent string IsDebug bool Timeout uint SecurityToken string IsCname bool IsPathStyle bool HTTPTimeout HTTPTimeout HTTPMaxConns HTTPMaxConns IsUseProxy bool ProxyHost string IsAuthProxy bool ProxyUser string ProxyPassword string IsEnableMD5 bool MD5Threshold int64 IsEnableCRC bool LogLevel int Logger *log.Logger UploadLimitSpeed int DownloadLimitSpeed int CredentialsProvider CredentialsProvider LocalAddr net.Addr AuthVersion AuthVersionType RedirectEnabled bool InsecureSkipVerify bool Region string CloudBoxId string Product string VerifyObjectStrict bool } ``` -------------------------------- ### Configure HTTP Proxy Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/configuration.md Set proxy settings during client initialization or update existing client configuration with authentication. ```go client, err := oss.New( endpoint, accessKeyID, accessKeySecret, oss.ProxyHost("http://proxy.company.com:8080"), ) // With authentication config := client.GetConfig() config.IsUseProxy = true config.ProxyHost = "http://proxy.company.com:8080" config.IsAuthProxy = true config.ProxyUser = "username" config.ProxyPassword = "password" ``` -------------------------------- ### Execute object copy within a bucket Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-bucket.md Demonstrates how to perform a copy operation and handle the resulting ETag. ```go result, err := bucket.CopyObject("original.txt", "copy.txt") if err != nil { log.Fatal(err) } fmt.Println("ETag:", result.ETag) ``` -------------------------------- ### List Objects with Go SDK Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/README.md Lists all objects within a specific bucket. ```go client, err := oss.New("Endpoint", "AccessKeyId", "AccessKeySecret") if err != nil { // HandleError(err) } bucket, err := client.Bucket("my-bucket") if err != nil { // HandleError(err) } lsRes, err := bucket.ListObjects() if err != nil { // HandleError(err) } for _, object := range lsRes.Objects { fmt.Println("Objects:", object.Key) } ``` -------------------------------- ### func (client Client) CreateBucket(bucketName string, options ...Option) error Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-client.md Creates a new bucket with optional ACL and storage class settings. ```APIDOC ## func (client Client) CreateBucket(bucketName string, options ...Option) error ### Description Creates a new bucket with optional ACL and storage class settings. ### Parameters - **bucketName** (string) - Required - Bucket name (3-255 characters, must start with letter/number) - **options** ([]Option) - Optional - Creation options: ACL, StorageClass, DataRedundancyType, ObjectHashFunction ### Returns - **error** - nil on success, error object otherwise ``` -------------------------------- ### Define HTTP Configuration Constants Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Constants for default header size limits, connection pooling, and time formatting. ```go const DefaultMaxHeaderBytes = 1 << 20 // 1 MB const DefaultMaxIdleConnsPerHost = 2 const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT" ``` -------------------------------- ### Configuring HTTP Transport Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Setting up a custom Transport for proxy, TLS, and connection settings. ```go tr := &http.Transport{ TLSClientConfig: &tls.Config{RootCAs: pool}, DisableCompression: true, } client := &http.Client{Transport: tr} resp, err := client.Get("https://example.com") ``` -------------------------------- ### Configure HTTP Connection Limits Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/configuration.md Manage connection pooling settings using the oss.HTTPMaxConns struct. ```go conns := oss.HTTPMaxConns{ MaxIdleConns: 100, // Total idle connections MaxIdleConnsPerHost: 100, // Idle connections per host MaxConnsPerHost: 0, // Max connections per host (0=unlimited) } ``` -------------------------------- ### Accept Encoding Option Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-options.md Sets the Accept-Encoding header for object retrieval. ```go AcceptEncoding(value string) Option ``` ```go reader, err := bucket.GetObject("file", oss.AcceptEncoding("gzip"), ) ``` -------------------------------- ### Set Custom Metadata with Meta Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-options.md Applies custom X-Oss-Meta-* headers to an object during upload. ```go Meta(key, value string) Option ``` ```go err := bucket.PutObject("file", reader, oss.Meta("custom-tag", "important"), oss.Meta("author", "john"), oss.Meta("department", "engineering"), ) ``` -------------------------------- ### Use Delimiter Option Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-options.md Groups objects by a delimiter to simulate folder structures. ```go result, err := bucket.ListObjects( oss.Prefix("data/"), oss.Delimiter("/"), ) // CommonPrefixes: ["data/2024/", "data/2025/"] ``` -------------------------------- ### Download Object to File in Go Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-bucket.md Downloads an object directly to a local file path. Uses a temporary file during the process to ensure atomic completion. ```go err := bucket.GetObjectToFile("myobject.txt", "/tmp/myobject.txt") if err != nil { log.Fatal(err) } ``` -------------------------------- ### FormFile Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Returns the first file for the provided form key. ```APIDOC ## func (*Request) FormFile(key string) ### Description Returns the first file for the provided form key. Calls ParseMultipartForm and ParseForm if necessary. ### Parameters - **key** (string) - Required - The form key for the file. ### Returns - **file** (multipart.File) - **header** (*multipart.FileHeader) - **err** (error) ``` -------------------------------- ### SetBucketLogging method and usage Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-client.md Configures access logging for a bucket, specifying the target bucket and prefix for log storage. ```go func (client Client) SetBucketLogging(bucketName, targetBucket, targetPrefix string, options ...Option) error ``` ```go err := client.SetBucketLogging("my-bucket", "my-log-bucket", "logs/") if err != nil { log.Fatal(err) } ``` -------------------------------- ### Define OSS Client Configuration Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/configuration.md The Config struct defines all available settings for the OSS client, including endpoint, credentials, timeouts, and proxy settings. ```go type Config struct { Endpoint string // OSS endpoint AccessKeyID string // Access key ID AccessKeySecret string // Access key secret RetryTimes uint // Retry attempts (default: 5) UserAgent string // User agent string IsDebug bool // Debug mode Timeout uint // Timeout in seconds SecurityToken string // STS token IsCname bool // Use CNAME IsPathStyle bool // Path-style URLs HTTPTimeout HTTPTimeout // HTTP timeouts HTTPMaxConns HTTPMaxConns // Connection limits IsUseProxy bool // Use proxy ProxyHost string // Proxy host IsAuthProxy bool // Proxy auth needed ProxyUser string // Proxy username ProxyPassword string // Proxy password IsEnableMD5 bool // Enable MD5 MD5Threshold int64 // MD5 threshold (16MB default) IsEnableCRC bool // Enable CRC (default: true) LogLevel int // Logging level Logger *log.Logger // Logger instance UploadLimitSpeed int // Upload speed limit (KB/s) DownloadLimitSpeed int // Download speed limit (KB/s) CredentialsProvider CredentialsProvider // Credentials provider LocalAddr net.Addr // Local client address AuthVersion AuthVersionType // Auth version AdditionalHeaders []string // Headers to sign RedirectEnabled bool // Follow redirects InsecureSkipVerify bool // Skip cert verification Region string // Region name CloudBoxId string // CloudBox ID Product string // Product type VerifyObjectStrict bool // Strict object name check } ``` -------------------------------- ### Configure SSL/TLS Verification Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/configuration.md Controls certificate verification. Disabling verification is not recommended for production environments. ```go // Skip certificate verification (NOT RECOMMENDED for production) config := client.GetConfig() config.InsecureSkipVerify = true // Or via option client, err := oss.New( endpoint, accessKeyID, accessKeySecret, oss.InsecureSkipVerify(true), ) ``` -------------------------------- ### Upload Objects Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/README.md Upload data to a bucket from a local file or an io.Reader. ```go bucket, err := client.Bucket("my-bucket") if err != nil { log.Fatal(err) } // Upload from file err = bucket.PutObjectFromFile("myobject", "/path/to/file.txt") if err != nil { log.Fatal(err) } // Upload from reader err = bucket.PutObject("myobject2", strings.NewReader("content")) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Hijack HTTP Connection Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Demonstrates how to take over an HTTP connection using the Hijacker interface to perform raw TCP communication. ```go package main import ( "fmt" "log" "net/http" ) func main() { http.HandleFunc("/hijack", func(w http.ResponseWriter, r *http.Request) { hj, ok := w.(http.Hijacker) if !ok { http.Error(w, "webserver doesn't support hijacking", http.StatusInternalServerError) return } conn, bufrw, err := hj.Hijack() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // Don't forget to close the connection: defer conn.Close() bufrw.WriteString("Now we're speaking raw TCP. Say hi: ") bufrw.Flush() s, err := bufrw.ReadString('\n') if err != nil { log.Printf("error reading string: %v", err) return } fmt.Fprintf(bufrw, "You said: %q\nBye.\n", s) bufrw.Flush() }) } ``` -------------------------------- ### Initiate Multipart Upload Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-multipart.md Initiates a new multipart upload session and retrieves a unique upload ID. ```go func (client Client) InitiateMultipartUpload(bucketName, objectKey string, options ...Option) (InitiateMultipartUploadResult, error) ``` ```go result, err := client.InitiateMultipartUpload("my-bucket", "large-file.zip") if err != nil { log.Fatal(err) } fmt.Println("Upload ID:", result.UploadID) ``` -------------------------------- ### Configure Server-Side Callback Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-options.md Sets the server-side callback configuration for an operation. ```go Callback(callback string) Option ``` -------------------------------- ### Download Objects Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/README.md Retrieve objects from a bucket to a local file or as an io.ReadCloser stream. ```go err := bucket.GetObjectToFile("myobject", "/tmp/downloaded-file.txt") if err != nil { log.Fatal(err) } // Or get as stream reader, err := bucket.GetObject("myobject") if err != nil { log.Fatal(err) } defer reader.Close() ``` -------------------------------- ### Client.Do Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Sends an HTTP request and returns an HTTP response using the client's configured policies. ```APIDOC ## func (c *Client) Do(req *Request) (resp *Response, err error) ### Description Do sends an HTTP request and returns an HTTP response, following policy (e.g. redirects, cookies, auth) as configured on the client. An error is returned if caused by client policy or if there was an HTTP protocol error. ``` -------------------------------- ### Multipart Upload Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/README.md Perform a multipart upload by initiating, uploading parts, and completing the process. ```go // Initiate result, err := client.InitiateMultipartUpload("bucket", "key") uploadID := result.UploadID // Upload part 1 fd, _ := os.Open("/path/to/file") part1, _ := client.UploadPart("bucket", "key", uploadID, 1, fd) // Complete parts := []oss.UploadPart{part1.Part} complete, _ := client.CompleteMultipartUpload("bucket", "key", uploadID, parts) fmt.Println("ETag:", complete.ETag) ``` -------------------------------- ### Serve directory with StripPrefix Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/sample/The Go Programming Language.html Use StripPrefix to modify the request URL path before passing it to a FileServer, allowing a directory to be served under an alternate URL path. ```go package main import ( "net/http" ) func main() { // To serve a directory on disk (/tmp) under an alternate URL // path (/tmpfiles/), use StripPrefix to modify the request // URL's path before the FileServer sees it: http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp")))) } ``` -------------------------------- ### Use MaxKeys Option Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-options.md Limits the number of objects returned in a single list request. ```go result, err := bucket.ListObjects( oss.Prefix("logs/"), oss.MaxKeys(1000), ) ``` -------------------------------- ### List Objects with V2 API Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-bucket.md Retrieves a list of objects from the bucket using the V2 API, supporting pagination and filtering options. ```go func (bucket Bucket) ListObjectsV2(options ...Option) (ListObjectsResultV2, error) ``` ```go result, err := bucket.ListObjectsV2(oss.MaxKeys(100)) if err != nil { log.Fatal(err) } for _, obj := range result.Objects { fmt.Println(obj.Key) } if result.IsTruncated { fmt.Println("Token:", result.NextContinuationToken) } ``` -------------------------------- ### Configure Object Storage Class Source: https://github.com/aliyun/aliyun-oss-go-sdk/blob/master/_autodocs/api-reference-options.md Sets the storage class for an object during upload. ```go ObjectStorageClass(storageClass StorageClassType) Option ``` ```go err := bucket.PutObject("archive.txt", reader, oss.ObjectStorageClass(oss.StorageArchive), ) ```