### Starting an HTTP Server with Custom Server Configuration in Go Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Shows how to create and start an HTTP server with more granular control over settings like address, timeouts, and maximum header size. ```go s := &http.Server{ Addr: ":8080", Handler: myHandler, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } log.Fatal(s.ListenAndServe()) ``` -------------------------------- ### Starting an HTTP Server with DefaultMux in Go Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Demonstrates starting an HTTP server that listens on a specified port and uses the DefaultServeMux for handling requests. Handlers can be registered using Handle and HandleFunc. ```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)) ``` -------------------------------- ### Making HTTP GET Request in Go Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Demonstrates how to perform a basic HTTP GET request using the http.Get function. Ensure the response body is closed after use. ```go resp, err := http.Get("[http://example.com/](http://example.com/)") if err != nil { // handle error } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) // ... ``` -------------------------------- ### Setting up a ServeMux with Handle and HandleFunc Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html This example demonstrates how to create a ServeMux and register handlers for different URL patterns. It includes a handler for a specific API path and a catch-all handler for the root path. ```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!") }) ``` -------------------------------- ### HTTP Server Implementation Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Details how to start an HTTP server using `ListenAndServe` and how to register handlers using `Handle` and `HandleFunc`. It also covers creating a custom `http.Server` for more advanced configuration. ```APIDOC ## HTTP Server Implementation ### Description Details how to start an HTTP server using `ListenAndServe` and how to register handlers using `Handle` and `HandleFunc`. It also covers creating a custom `http.Server` for more advanced configuration. ### Basic Server Setup `http.ListenAndServe` starts a server with a specified address and handler. If the handler is `nil`, `DefaultServeMux` is used. ```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)) ``` ### Custom Server Configuration Create a custom `http.Server` to configure advanced settings like timeouts and maximum header bytes. ```go s := &http.Server{ Addr: ":8080", Handler: myHandler, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } log.Fatal(s.ListenAndServe()) ``` ``` -------------------------------- ### Basic HTTP Server Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html A simple Go program that sets up an HTTP server to respond with 'hello, world!' to requests on the /hello path. It uses ListenAndServe to start the server on port 12345. ```go package main import ( io "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) } } ``` -------------------------------- ### ListenAndServe Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html ListenAndServe starts an HTTP server on a specified TCP address and uses a handler to process incoming connections. If no handler is provided, it defaults to DefaultServeMux. ```APIDOC ## ListenAndServe ### Description ListenAndServe listens on the TCP network address addr and then calls Serve with handler to handle requests on incoming connections. Handler is typically nil, in which case the DefaultServeMux is used. ### Signature func ListenAndServe(addr [string], handler [Handler]) [error] ### Parameters - **addr** (string) - The TCP network address to listen on (e.g., ":8080"). - **handler** ([Handler](https://golang.org/pkg/net/http/#Handler)) - The handler to use for incoming requests. If nil, DefaultServeMux is used. ### Returns - **error** - An error if the server fails to start or encounters an issue. ``` -------------------------------- ### List Objects in Bucket in Go Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/README.md Initializes a KS3 client, gets a bucket object, and lists all objects within the bucket. Ensure you have the correct endpoint, AccessKeyId, AccessKeySecret, and bucket name. ```go client, err := ks3.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) } ``` -------------------------------- ### Serve Directory with StripPrefix Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Use http.StripPrefix to serve a directory under a different URL path. This example serves the /tmp directory under the /tmpfiles/ 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")))) } ``` -------------------------------- ### Basic HTTPS Server Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html An example of setting up an HTTPS server in Go using ListenAndServeTLS. This server responds with a plain text message and requires 'cert.pem' and 'key.pem' for TLS configuration. It listens on port 10443. ```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) } } ``` -------------------------------- ### Download Object to File in Go Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/README.md Initializes a KS3 client, gets a bucket object, and downloads an object from the bucket to a local file. Ensure you have the correct endpoint, AccessKeyId, AccessKeySecret, bucket name, object key, and local file path. ```go client, err := ks3.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) } ``` -------------------------------- ### HTTP Hijacking Example Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html This snippet demonstrates how to hijack an HTTP connection to communicate directly over TCP. It requires the ResponseWriter to implement the http.Hijacker interface. Ensure the connection is closed after use. ```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() }) } ``` -------------------------------- ### Perform a GET Request in Go Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Use http.Get to fetch the content of a URL. This function automatically follows redirects. Remember to close the response body. ```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) } ``` -------------------------------- ### Upload Object from File in Go Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/README.md Initializes a KS3 client, gets a bucket object, and uploads a file to the bucket. Ensure you have the correct endpoint, AccessKeyId, AccessKeySecret, bucket name, object key, and local file path. ```go client, err := ks3.New("Endpoint", "AccessKeyId", "AccessKeySecret") if err != nil { // HandleError(err) } bucket, err := client.Bucket("my-bucket") if err != nil { // HandleError(err) } err = bucket.PutObjectFromFile("my-object", "LocalFile") if err != nil { // HandleError(err) } ``` -------------------------------- ### Client.Get Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Issues a GET to the specified URL. If the response is a redirect code, Get follows the redirect after calling the Client's CheckRedirect function. An error is returned if the Client's CheckRedirect function fails or if there was an HTTP protocol error. ```APIDOC ## Client.Get ### Description Issues a GET request to the specified URL. It automatically follows redirects (301, 302, 303, 307) by calling the Client's CheckRedirect function. An error is returned for client redirect failures or HTTP protocol errors. Non-2xx responses do not cause an error. ### Method GET ### Endpoint [url] ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go resp, err := client.Get("http://example.com") ``` ### Response #### Success Response (200) - **resp** (*http.Response) - The HTTP response received. - **err** (error) - An error if one occurred during the request. #### Response Example ```json // Response body structure depends on the actual HTTP response { "StatusCode": 200, "Header": { "Content-Type": ["text/html"] }, "Body": "..." } ``` ``` -------------------------------- ### Serve HTTP Requests with FileServer Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Use http.FileServer with http.Dir to serve files from the operating system's file system. This example serves files from /usr/share/doc on port 8080. ```Go package main import ( "log" "net/http" ) func main() { // Simple static webserver: log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc")))) } ``` -------------------------------- ### Header.Get Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Get retrieves the first value associated with a given key from the HTTP header. Returns an empty string if the key is not found. ```APIDOC ## func (Header) Get ### Description Get gets the first value associated with the given key. If there are no values associated with the key, Get returns "". To access multiple values of a key, access the map directly with CanonicalHeaderKey. ### Signature func (h Header) Get(key string) string ``` -------------------------------- ### Client Methods Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Provides methods for making HTTP requests using the Client type. This includes executing requests, and performing GET, HEAD, POST, and POSTForm operations. ```APIDOC ## Client.Do ### Description Executes a given HTTP request and returns the HTTP response. ### Method * Client.Do ### Parameters * **req** (*Request) - The HTTP request to execute. ### Response * **resp** (*Response) - The HTTP response. * **err** (error) - An error if the request failed. ## Client.Get ### Description Performs a GET request to the specified URL. ### Method * Client.Get ### Parameters * **url** (string) - The URL to send the GET request to. ### Response * **resp** (*Response) - The HTTP response. * **err** (error) - An error if the request failed. ## Client.Head ### Description Performs a HEAD request to the specified URL. ### Method * Client.Head ### Parameters * **url** (string) - The URL to send the HEAD request to. ### Response * **resp** (*Response) - The HTTP response. * **err** (error) - An error if the request failed. ## Client.Post ### Description Performs a POST request to the specified URL with a specified content type and body. ### Method * Client.Post ### Parameters * **url** (string) - The URL to send the POST request to. * **bodyType** (string) - The content type of the request body. * **body** (io.Reader) - The request body. ### Response * **resp** (*Response) - The HTTP response. * **err** (error) - An error if the request failed. ## Client.PostForm ### Description Performs a POST request to the specified URL with form data. ### Method * Client.PostForm ### Parameters * **url** (string) - The URL to send the POST request to. * **data** (url.Values) - The form data to send. ### Response * **resp** (*Response) - The HTTP response. * **err** (error) - An error if the request failed. ``` -------------------------------- ### Request and Response Utilities Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Utility functions for parsing times, setting cookies, and getting status text. ```APIDOC ## ParseTime ### Description Parses a time string into a time.Time object. ### Method * ParseTime ### Parameters * **text** (string) - The time string to parse. ### Response * **t** (time.Time) - The parsed time. * **err** (error) - An error if parsing fails. ## Redirect ### Description Sends an HTTP redirect response to the client. ### Method * Redirect ### Parameters * **w** (ResponseWriter) - The ResponseWriter to write the response to. * **r** (*Request) - The HTTP request. * **urlStr** (string) - The URL to redirect to. * **code** (int) - The HTTP status code for the redirect (e.g., 301, 302). ### Response * **error** (error) - An error if writing the response fails. ## SetCookie ### Description Adds a Set-Cookie header to the HTTP response. ### Method * SetCookie ### Parameters * **w** (ResponseWriter) - The ResponseWriter to write the response to. * **cookie** (*Cookie) - The cookie to set. ### Response * **error** (error) - An error if writing the header fails. ## StatusText ### Description Returns the text for the HTTP status code. ### Method * StatusText ### Parameters * **code** (int) - The HTTP status code. ### Response * **string** - The text representation of the status code. ``` -------------------------------- ### Writing HTTP Response with Trailers Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html This example demonstrates how to declare and set HTTP trailers in a response. Trailers are declared using the 'Trailer' header before calling WriteHeader, and then set using the ResponseWriter's Header() method before the response is fully sent. ```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. }) } ``` -------------------------------- ### Get First Header Value Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Retrieves the first value associated with a given key from an HTTP header. Returns an empty string if the key is not found. ```Go func (h Header) Get(key string) string ``` -------------------------------- ### Client.Head Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Issues a HEAD request to the specified URL. It follows redirects similarly to the Get method. An error is returned for client redirect failures or HTTP protocol errors. ```APIDOC ## Client.Head ### Description Issues a HEAD request to the specified URL. It automatically follows redirects (301, 302, 303, 307) by calling the Client's CheckRedirect function. An error is returned for client redirect failures or HTTP protocol errors. ### Method HEAD ### Endpoint [url] ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go resp, err := client.Head("http://example.com/resource") ``` ### Response #### Success Response (200) - **resp** (*http.Response) - The HTTP response received (typically with no body for HEAD requests). - **err** (error) - An error if one occurred during the request. #### Response Example ```json // Response headers are relevant for HEAD requests { "StatusCode": 200, "Header": { "Content-Length": ["1234"] } } ``` ``` -------------------------------- ### HTTP Client Functions Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Provides functions for making HTTP requests. These include GET, HEAD, POST, and POSTForm, allowing for various types of client-initiated HTTP interactions. ```APIDOC ## HTTP Client Functions ### Description Provides functions for making HTTP requests. These include GET, HEAD, POST, and POSTForm, allowing for various types of client-initiated HTTP interactions. ### Functions - **Get(url string)**: Sends a GET request to the specified URL and returns the response and any error encountered. - **Head(url string)**: Sends a HEAD request to the specified URL and returns the response and any error encountered. - **Post(url string, bodyType string, body io.Reader)**: Sends a POST request to the specified URL with the given content type and request body. Returns the response and any error encountered. - **PostForm(url string, data url.Values)**: Sends a POST request to the specified URL with form data. Returns the response and any error encountered. - **ReadResponse(r *bufio.Reader, req *Request)**: Reads an HTTP response from a buffered reader, associated with a given request. Returns the response and any error encountered. ``` -------------------------------- ### http.Get Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Issues a GET request to the specified URL and follows redirects up to a maximum of 10. It returns a Response and an error. The caller is responsible for closing the response body. ```APIDOC ## GET [url] ### Description Issues a GET request to the specified URL. If the response is a redirect, it follows the redirect up to a maximum of 10 redirects. ### Method GET ### Endpoint [url] ### Parameters #### Path Parameters - **url** (string) - Required - The URL to fetch. ### Response #### Success Response (200 OK) - **resp** (*http.Response) - The HTTP response. - **err** (error) - An error if the request failed or if there were too many redirects. ### Notes - A non-2xx response does not cause an error. - The caller must close `resp.Body`. - This is a wrapper around `DefaultClient.Get`. ``` -------------------------------- ### HTTP Client Functions Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Provides high-level functions for making common HTTP requests like GET, POST, and POSTForm. It also demonstrates how to read the response body and the importance of closing the response body. ```APIDOC ## HTTP Client Functions ### Description Provides high-level functions for making common HTTP requests like GET, POST, and POSTForm. It also demonstrates how to read the response body and the importance of closing the response body. ### Functions - `http.Get(url string) (*Response, error)`: Makes a GET request to the specified URL. - `http.Post(url string, contentType string, body io.Reader) (*Response, error)`: Makes a POST request to the specified URL with the given content type and request body. - `http.PostForm(url string, data url.Values) (*Response, error)`: Makes a POST request to the specified URL with form-encoded data. ### Response Body Handling It is crucial to close the response body after use to free up resources. ```go resp, err := http.Get("[http://example.com/](http://example.com/)") if err != nil { // handle error } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) // ... ``` ``` -------------------------------- ### Delete Object in Go Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/README.md Initializes a KS3 client, gets a bucket object, and deletes a specified object from the bucket. Ensure you have the correct endpoint, AccessKeyId, AccessKeySecret, bucket name, and object key. ```go client, err := ks3.New("Endpoint", "AccessKeyId", "AccessKeySecret") if err != nil { // HandleError(err) } bucket, err := client.Bucket("my-bucket") if err != nil { // HandleError(err) } err = bucket.DeleteObject("my-object") if err != nil { // HandleError(err) } ``` -------------------------------- ### Basic Hello World in Go Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html A simple 'Hello, World!' program in Go, demonstrating basic syntax and output. ```go package main import "fmt" func main() { fmt.Println("Hello, 世界") } ``` -------------------------------- ### Get Cookies from HTTP Response in Go Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html The Cookies method on an http.Response parses and returns any cookies set in the Set-Cookie headers. ```Go func (r *Response) Cookies() []*Cookie ``` -------------------------------- ### Custom HTTP Client Configuration in Go Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Demonstrates creating a custom HTTP client with a redirect policy. Clients should be created once and reused. ```go client := &http.Client{ CheckRedirect: redirectPolicyFunc, } resp, err := client.Get("[http://example.com](http://example.com/)") // ... ``` -------------------------------- ### List Buckets in Go Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/README.md Initializes a KS3 client and lists all buckets associated with the account. Ensure you have the correct endpoint, AccessKeyId, and AccessKeySecret. ```go client, err := ks3.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) } ``` -------------------------------- ### Create Bucket in Go Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/README.md Initializes a KS3 client and creates a new bucket with the specified name. Ensure you have the correct endpoint, AccessKeyId, and AccessKeySecret. ```go client, err := ks3.New("Endpoint", "AccessKeyId", "AccessKeySecret") if err != nil { // HandleError(err) } err = client.CreateBucket("my-bucket") if err != nil { // HandleError(err) } ``` -------------------------------- ### Creating and Performing HTTP Requests in Go Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Shows how to create a custom HTTP request and send it using a configured client. Headers can be added to the request. ```go req, err := http.NewRequest("GET", "[http://example.com](http://example.com/)", nil) // ... req.Header.Add("If-None-Match", `W/"wyzzy"`) resp, err := client.Do(req) // ... ``` -------------------------------- ### Custom HTTP Transport Configuration in Go Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Illustrates configuring a custom HTTP transport for advanced settings like TLS and compression. Transports should be created once and reused. ```go tr := &http.Transport{ TLSClientConfig: &tls.Config{RootCAs: pool}, DisableCompression: true, } client := &http.Client{Transport: tr} resp, err := client.Get("[https://example.com](https://example.com/)") // ... ``` -------------------------------- ### Making HTTP POST Request in Go Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Shows how to make an HTTP POST request with a specified content type and body. ```go resp, err := http.Post("[http://example.com/upload](http://example.com/upload)", "image/jpeg", &buf) // ... ``` -------------------------------- ### Custom HTTP Client Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Demonstrates how to create a custom HTTP client for more control over request behavior, such as redirect policies. It also shows how to create a request manually and set custom headers. ```APIDOC ## Custom HTTP Client ### Description Demonstrates how to create a custom HTTP client for more control over request behavior, such as redirect policies. It also shows how to create a request manually and set custom headers. ### Client Configuration Create a `http.Client` to customize settings like redirect policy. ```go client := &http.Client{ CheckRedirect: redirectPolicyFunc, } resp, err := client.Get("[http://example.com](http://example.com/)") // ... ``` ### Creating and Executing Requests Use `http.NewRequest` to create a request object and then use the client's `Do` method to execute it. Custom headers can be added to the request. ```go req, err := http.NewRequest("GET", "[http://example.com](http://example.com/)", nil) // ... req.Header.Add("If-None-Match", `W/"wyzzy"`) resp, err := client.Do(req) // ... ``` ``` -------------------------------- ### Making HTTP POSTForm Request in Go Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Illustrates how to send form data using an HTTP POST request. ```go resp, err := http.PostForm("[http://example.com/form](http://example.com/form)", url.Values{"key": {"Value"}, "id": {"123"}}) // ... ``` -------------------------------- ### Get Location URL from HTTP Response in Go Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html The Location method on an http.Response extracts the URL from the "Location" header. It resolves relative redirects and returns an error if the header is absent. ```Go func (r *Response) Location() (*url.URL, error) ``` -------------------------------- ### Dir.Open Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html The Open method on Dir implements the FileSystem interface, providing access to files within a directory. ```APIDOC ## func (Dir) Open ### Description Opens the named file within the directory. ### Signature func (d Dir) Open(name string) (File, error) ### Parameters #### Path Parameters - **name** (string) - The name of the file to open. ``` -------------------------------- ### Serve Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Serve 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. ```APIDOC ## Serve *Server.Serve ### Description Serve 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. ### Method (Implicitly called by ListenAndServe/ListenAndServeTLS) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response None explicitly defined, handles HTTP requests. #### Response Example None ``` -------------------------------- ### Serve Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Listens for incoming HTTP connections on a given network listener and serves requests using the provided handler. If the handler is nil, the DefaultServeMux is used. ```APIDOC ## Serve ### Description Accepts incoming HTTP connections on the listener and serves requests using the provided handler. If handler is nil, DefaultServeMux is used. ### Signature func Serve(l net.Listener, handler http.Handler) error ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None explicitly provided in source. ### Response #### Success Response None (returns error if serving fails) #### Response Example None explicitly provided in source. ``` -------------------------------- ### ServeFile Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Serves the contents of a named file or directory in response to an HTTP request. This is a convenient way to serve static files. ```APIDOC ## ServeFile ### Description Replies to a request with the contents of the named file or directory. ### Signature func ServeFile(w http.ResponseWriter, r *http.Request, name string) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None explicitly provided in source. ### Response #### Success Response None (writes to ResponseWriter) #### Response Example None explicitly provided in source. ``` -------------------------------- ### ServeMux.Handle Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Registers a handler for a specific URL pattern. If a handler already exists for the pattern, this function will panic. ```APIDOC ## func (mux *ServeMux) Handle func (mux *ServeMux) Handle(pattern string, handler Handler) Handle registers the handler for the given pattern. If a handler already exists for pattern, Handle panics. ▹ Example 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!") }) ``` -------------------------------- ### Package http Index Functions Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Lists key functions available in the net/http package, including those for handling requests, responses, and server operations. ```APIDOC ## Package http Index Functions ### Description Lists key functions available in the net/http package, including those for handling requests, responses, and server operations. ### Functions - `func CanonicalHeaderKey(s string) string`: Returns the canonical form of the HTTP header key. - `func DetectContentType(data []byte) string`: Returns the Content-Type of the given data. - `func Error(w ResponseWriter, error string, code int)`: Writes an HTTP error message to the ResponseWriter. - `func Handle(pattern string, handler Handler)`: Registers a handler for a given pattern in `DefaultServeMux`. - `func HandleFunc(pattern string, handler func(ResponseWriter, *Request))`: Registers a function handler for a given pattern in `DefaultServeMux`. - `func ListenAndServe(addr string, handler Handler) error`: Starts an HTTP server with the given address and handler. - `func ListenAndServeTLS(addr string, certFile string, keyFile string, handler Handler) error`: Starts an HTTPS server. - `func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser`: Wraps an io.ReadCloser with a limit on the number of bytes that can be read. - `func NotFound(w ResponseWriter, r *Request)`: Sends a "404 Not Found" response. - `func ParseHTTPVersion(vers string) (major, minor int, ok bool)`: Parses an HTTP version string. ``` -------------------------------- ### HTTP Server Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html The `Server` type defines parameters for running an HTTP server. ```APIDOC ## HTTP Server ### Description The `Server` type defines parameters for running an HTTP server. ### Methods - **ListenAndServe()**: Starts an HTTP server with a listener. - **ListenAndServeTLS(certFile, keyFile string)**: Starts an HTTPS server with a listener, using the provided certificate and key files. - **Serve(l net.Listener)**: Runs the HTTP server on the given listener. - **SetKeepAlivesEnabled(v bool)**: Enables or disables keep-alives for the server. ``` -------------------------------- ### Perform a POST Request in Go Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Use http.Post to send a POST request. Provide the URL, content type, and a reader for the request body. The response body must be closed. ```Go func Post(url string, bodyType string, body io.Reader) (resp *Response, err error) ``` -------------------------------- ### FileServer Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html FileServer returns an HTTP handler that serves files from a given FileSystem. ```APIDOC ## func FileServer ### Description FileServer returns a handler that serves HTTP requests with the contents of the file system rooted at root. ### Signature func FileServer(root FileSystem) Handler ### Parameters #### Path Parameters - **root** (FileSystem) - The root of the file system to serve. ### Example ```go package main import ( "log" "net/http" ) func main() { // Simple static webserver: log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc")))) } ``` ``` -------------------------------- ### (*Response) ProtoAtLeast Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html ProtoAtLeast reports whether the HTTP protocol used in the response is at least major.minor. ```APIDOC ## (*Response) ProtoAtLeast ### Description ProtoAtLeast reports whether the HTTP protocol used in the response is at least major.minor. ### Method Signature func (r *Response) ProtoAtLeast(major, minor int) bool ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - **bool**: Returns true if the HTTP protocol version is at least major.minor, false otherwise. ### Response Example None ``` -------------------------------- ### ServeContent Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Serves HTTP requests using content from an io.ReadSeeker. It handles Range requests, sets MIME types, and manages If-Modified-Since headers. It can also deduce content type from the filename or content itself. ```APIDOC ## ServeContent ### Description Replies to a request using the content from an io.ReadSeeker. It handles Range, If-Modified-Since, and ETag headers, and sets the MIME type. ### Signature func ServeContent(w http.ResponseWriter, req *http.Request, name string, modtime time.Time, content io.ReadSeeker) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None explicitly provided in source. ### Response #### Success Response None (writes to ResponseWriter) #### Response Example None explicitly provided in source. ``` -------------------------------- ### Delete Bucket in Go Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/README.md Initializes a KS3 client and deletes the specified bucket. The bucket must be empty before it can be deleted. Ensure you have the correct endpoint, AccessKeyId, and AccessKeySecret. ```go client, err := ks3.New("Endpoint", "AccessKeyId", "AccessKeySecret") if err != nil { // HandleError(err) } err = client.DeleteBucket("my-bucket") if err != nil { // HandleError(err) } ``` -------------------------------- ### ListenAndServeTLS Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html ListenAndServeTLS listens on the TCP network address srv.Addr and then calls Serve to handle requests on incoming TLS connections. Filenames containing a certificate and matching private key for the server must be provided if the Server's TLSConfig.Certificates is not populated. ```APIDOC ## ListenAndServeTLS *Server.ListenAndServeTLS ### Description ListenAndServeTLS listens on the TCP network address srv.Addr and then calls Serve to handle requests on incoming TLS connections. Filenames containing a certificate and matching private key for the server must be provided if the Server's TLSConfig.Certificates is not populated. ### Method POST (Implicit) ### Endpoint / ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None explicitly defined, handles HTTP requests. #### Response Example None ``` -------------------------------- ### Write Header in Wire Format Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Writes an HTTP header in its standard wire format to a given writer. ```Go func (h Header) Write(w io.Writer) error ``` -------------------------------- ### HandlerFunc.ServeHTTP Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html ServeHTTP is a method on HandlerFunc that calls the underlying function, adapting it to the Handler interface. ```APIDOC ## func (HandlerFunc) ServeHTTP ### Description ServeHTTP calls f(w, r). ### Signature func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) ``` -------------------------------- ### Header.Write Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Write serializes the HTTP header into wire format, writing it to the provided io.Writer. ```APIDOC ## func (Header) Write ### Description Write writes a header in wire format. ### Signature func (h Header) Write(w io.Writer) error ``` -------------------------------- ### ListenAndServeTLS Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html ListenAndServeTLS is similar to ListenAndServe but is used for HTTPS connections. It requires certificate and key files for secure communication. ```APIDOC ## ListenAndServeTLS ### Description ListenAndServeTLS acts identically to ListenAndServe, except that it expects HTTPS connections. Additionally, files containing a certificate and matching private key for the server must be provided. ### Signature func ListenAndServeTLS(addr [string], certFile [string], keyFile [string], handler [Handler]) [error] ### Parameters - **addr** (string) - The TCP network address to listen on (e.g., ":8443"). - **certFile** (string) - Path to the TLS certificate file. - **keyFile** (string) - Path to the TLS private key file. - **handler** ([Handler](https://golang.org/pkg/net/http/#Handler)) - The handler to use for incoming requests. If nil, DefaultServeMux is used. ### Returns - **error** - An error if the server fails to start or encounters an issue. ``` -------------------------------- ### Registering a Custom File Transport Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html This snippet shows how to register a custom RoundTripper for the 'file' protocol with an http.Transport. It's useful for serving local files over HTTP. ```Go t := &http.Transport{} t.RegisterProtocol("file", http.NewFileTransport(http.Dir("/"))) c := &http.Client{Transport: t} res, err := c.Get("file:///etc/passwd") ``` -------------------------------- ### ProtoAtLeast Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Reports whether the HTTP protocol used in the request is at least the specified major.minor version. ```APIDOC ## ProtoAtLeast ### Description Reports whether the HTTP protocol used in the request is at least major.minor. ### Method (none specified, typically called on a Request object) ### Parameters - **major** (int) - The major version number. - **minor** (int) - The minor version number. ### Response - bool - True if the protocol version is at least major.minor, false otherwise. ``` -------------------------------- ### Handle Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Handle registers the handler for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched. ```APIDOC ## Handle ### Description Handle registers the handler for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched. ### Signature func Handle(pattern string, handler Handler) ``` -------------------------------- ### ListenAndServe Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html ListenAndServe 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. ```APIDOC ## ListenAndServe *Server.ListenAndServe ### Description ListenAndServe 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. ### Method POST (Implicit) ### Endpoint / ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None explicitly defined, handles HTTP requests. #### Response Example None ``` -------------------------------- ### ServeMux.Handler Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Returns the handler to use for a given request, based on the request's method, host, and path. It also returns the registered pattern that matches the request. ```APIDOC ## func (mux *ServeMux) Handler func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string) Handler returns the handler to use for the given request, consulting r.Method, r.Host, and r.URL.Path. It always returns a non-nil handler. If the path is not in its canonical form, the handler will be an internally-generated handler that redirects to the canonical path. Handler also returns the registered pattern that matches the request or, in the case of internally-generated redirects, the pattern that will match after following the redirect. If there is no registered handler that applies to the request, Handler returns a “page not found” handler and an empty pattern. ``` -------------------------------- ### ServeMux.HandleFunc Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Registers a handler function for a specific URL pattern. This is a convenient way to register functions as handlers. ```APIDOC ## func (mux *ServeMux) HandleFunc func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) HandleFunc registers the handler function for the given pattern. ``` -------------------------------- ### ProxyFromEnvironment Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Retrieves the proxy URL from environment variables for a given HTTP request. It respects HTTP_PROXY, HTTPS_PROXY, and NO_PROXY settings, with HTTPS_PROXY taking precedence for HTTPS requests. It can return a nil URL if no proxy is needed or defined. ```APIDOC ## ProxyFromEnvironment ### Description Retrieves the proxy URL from environment variables (HTTP_PROXY, HTTPS_PROXY, NO_PROXY) for a given request. HTTPS_PROXY is prioritized for HTTPS requests. It returns a nil URL and error if no proxy is defined or applicable. ### Signature func ProxyFromEnvironment(req *http.Request) (*url.URL, error) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None explicitly provided in source. ### Response #### Success Response - **URL** (*url.URL) - The proxy URL to use. - **error** (error) - An error if the environment variable format is invalid. #### Response Example None explicitly provided in source. ``` -------------------------------- ### Perform a HEAD Request in Go Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Use http.Head to send a HEAD request to a URL. This is useful for retrieving headers without the response body. It also follows redirects. ```Go func Head(url string) (resp *Response, err error) ``` -------------------------------- ### ServeHTTP Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html ServeHTTP dispatches the request to the handler whose pattern most closely matches the request URL. It is a method of the ServeMux type. ```APIDOC ## ServeHTTP ServeMux.ServeHTTP ### Description ServeHTTP dispatches the request to the handler whose pattern most closely matches the request URL. ### Method (Implicitly called by the HTTP server) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response None explicitly defined, handles HTTP requests. #### Response Example None ``` -------------------------------- ### Set Header Key-Value Pair Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Sets the header entries associated with a key to a single value. Replaces any existing values for that key. ```Go func (h Header) Set(key, value string) ``` -------------------------------- ### Server Functions Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Functions for serving HTTP requests and handling responses. ```APIDOC ## Serve ### Description Listens on the provided network listener and serves HTTP requests using the given handler. ### Method * Serve ### Parameters * **l** (net.Listener) - The network listener to accept connections from. * **handler** (Handler) - The handler to serve requests with. ### Response * **error** (error) - An error if the server fails to start or run. ## ServeContent ### Description Serves HTTP requests with the content found in the provided ReadSeeker. ### Method * ServeContent ### Parameters * **w** (ResponseWriter) - The ResponseWriter to write the response to. * **req** (*Request) - The HTTP request. * **name** (string) - The name of the content (e.g., filename). * **modtime** (time.Time) - The modification time of the content. * **content** (io.ReadSeeker) - The content to serve. ### Response * **error** (error) - An error if writing the response fails. ## ServeFile ### Description Serves an HTTP request by reading the content from the specified file. ### Method * ServeFile ### Parameters * **w** (ResponseWriter) - The ResponseWriter to write the response to. * **r** (*Request) - The HTTP request. * **name** (string) - The path to the file to serve. ### Response * **error** (error) - An error if reading or writing the file fails. ``` -------------------------------- ### Custom HTTP Transport Source: https://github.com/ks3sdklib/ksyun-ks3-go-sdk/blob/master/sample/The Go Programming Language.html Explains how to configure a custom `http.Transport` to control lower-level settings like proxy configuration, TLS settings, and compression. This custom transport is then used with an `http.Client`. ```APIDOC ## Custom HTTP Transport ### Description Explains how to configure a custom `http.Transport` to control lower-level settings like proxy configuration, TLS settings, and compression. This custom transport is then used with an `http.Client`. ### Transport Configuration Create a `http.Transport` to customize settings like TLS configuration and compression. ```go tr := &http.Transport{ TLSClientConfig: &tls.Config{RootCAs: pool}, DisableCompression: true, } client := &http.Client{Transport: tr} resp, err := client.Get("[https://example.com](https://example.com/)") ``` **Note:** Clients and Transports are safe for concurrent use and should be reused. ```