### Install Requests Library Source: https://context7.com/wangluozhe/requests/llms.txt Install the library using Go modules. ```bash go get github.com/wangluozhe/requests ``` -------------------------------- ### Install Specific Version of Requests Source: https://github.com/wangluozhe/requests/blob/main/README.md Use 'go get' with a version tag to install a specific release of the requests library. ```bash go get github.com/wangluozhe/requests@v1.5.2 ``` -------------------------------- ### Send GET Request Source: https://github.com/wangluozhe/requests/blob/main/README.md Imports necessary packages and sends a GET request to a specified URL. The response object can be used to retrieve information. ```go import ( "github.com/wangluozhe/requests" "github.com/wangluozhe/requests/url" ) r, err := requests.Get("https://api.github.com/events", nil) ``` -------------------------------- ### Sending Cookies with a Request in Go Source: https://github.com/wangluozhe/requests/blob/main/README.md Demonstrates how to send custom cookies to a server using the 'Cookies' parameter in a request. This example uses the http.cookiejar. ```go req := url.NewRequest() cookies,_ := cookiejar.New(nil) // cookies := url.NewCookies() // 推荐使用这种 urls, _ := url.Parse("http://httpbin.org/cookies") cookies.SetCookies(urls,[]*http.Cookie{&http.Cookie{ Name: "cookies_are", Value: "working", }}) req.Cookies = cookies r, err := requests.Get("http://httpbin.org/cookies", req) if err != nil { fmt.Println(err) } fmt.Println(r.Text()) {"cookies": {"cookies_are": "working"}} ``` -------------------------------- ### Set Proxy for Requests Source: https://github.com/wangluozhe/requests/blob/main/README.md Shows how to set a proxy for a GET request by assigning a proxy string to the Proxies field of the url.Request struct. Supports authentication. ```go req := url.NewRequest() req.Proxies = "http://127.0.0.1:32768" // 设置带账号密码的代理:req.Proxies = "http://username:password@ip:port" r, err := requests.Get("https://api.github.com/events", req) ``` -------------------------------- ### Send GET Request with Requests Go Source: https://context7.com/wangluozhe/requests/llms.txt Sends an HTTP GET request using the default session. Pass nil for no request options. Supports query parameters. ```go package main import ( "fmt" "github.com/wangluozhe/requests" "github.com/wangluozhe/requests/url" ) func main() { // Simple GET with no options r, err := requests.Get("https://httpbin.org/get", nil) if err != nil { fmt.Println("Error:", err) return } fmt.Println("Status:", r.StatusCode) // 200 fmt.Println("Body:", r.Text()) // GET with query parameters params := url.NewParams() params.Set("page", "1") params.Set("limit", "10") r, err = requests.Get("https://httpbin.org/get", &url.Request{Params: params}) if err != nil { fmt.Println("Error:", err) return } fmt.Println("URL:", r.Url) // https://httpbin.org/get?page=1&limit=10 } ``` -------------------------------- ### Other HTTP Methods with Requests Go Source: https://context7.com/wangluozhe/requests/llms.txt Convenience functions for PUT, DELETE, and HEAD requests. Accepts the same signature as POST and GET. ```go package main import ( "fmt" "github.com/wangluozhe/requests" "github.com/wangluozhe/requests/url" ) func main() { // PUT request with JSON req := url.NewRequest() req.Json = map[string]interface{}{"status": "active"} r, err := requests.Put("https://httpbin.org/put", req) if err != nil { fmt.Println(err) return } fmt.Println("PUT status:", r.StatusCode) // DELETE request r, err = requests.Delete("https://httpbin.org/delete", nil) if err != nil { fmt.Println(err) return } fmt.Println("DELETE status:", r.StatusCode) // HEAD request (redirects disabled automatically) r, err = requests.Head("https://httpbin.org/get", nil) if err != nil { fmt.Println(err) return } fmt.Println("HEAD Content-Type:", r.Headers.Get("Content-Type")) } ``` -------------------------------- ### requests.Get Source: https://context7.com/wangluozhe/requests/llms.txt Sends an HTTP GET request using the default session. It can be used with or without request options like query parameters. ```APIDOC ## requests.Get — Send a GET request Sends an HTTP GET request using the default session. Returns a `*models.Response` and an error. Pass `nil` as the second argument when no request options are needed. ### Method GET ### Endpoint (URL provided in the function call) ### Parameters #### Path Parameters None #### Query Parameters - **(Implicitly set via `url.Request.Params`)** #### Request Body None ### Request Example ```go package main import ( "fmt" "github.com/wangluozhe/requests" "github.com/wangluozhe/requests/url" ) func main() { // Simple GET with no options r, err := requests.Get("https://httpbin.org/get", nil) if err != nil { fmt.Println("Error:", err) return } fmt.Println("Status:", r.StatusCode) // 200 fmt.Println("Body:", r.Text()) // GET with query parameters params := url.NewParams() params.Set("page", "1") params.Set("limit", "10") r, err = requests.Get("https://httpbin.org/get", &url.Request{Params: params}) if err != nil { fmt.Println("Error:", err) return } fmt.Println("URL:", r.Url) // https://httpbin.org/get?page=1&limit=10 } ``` ### Response #### Success Response (200) - **StatusCode** (int) - The HTTP status code of the response. - **Text()** (string) - Returns the response body as a string. - **Url** (string) - The final URL after any redirects. ``` -------------------------------- ### Create Image from Binary Response Source: https://github.com/wangluozhe/requests/blob/main/README.md Demonstrates how to create an image file from a binary response. It shows two methods for writing the response body: using `io.Copy` with `r.Body` or writing directly from `resp.Content`. ```go package main import "github.com/wangluozhe/requests" func main(){ r, err := requests.Get("图片URL", nil) if err != nil { fmt.Println(err) } jpg,_ := os.Create("1.jpg") io.Copy(jpg,r.Body) // 第一种 //jpg.Write(resp.Content) // 第二种 } ``` -------------------------------- ### Enabling Redirects for HEAD Requests in Go Source: https://github.com/wangluozhe/requests/blob/main/README.md Demonstrates how to enable redirect handling for HEAD requests by setting 'AllowRedirects' to true. ```go req := url.NewRequest() req.AllowRedirects = url.Bool(true) r, err := requests.Get("http://github.com", req) if err != nil { fmt.Println(err) } fmt.Println(r.Url) https://github.com/ fmt.Println(r.History) [0xc0001803f0] ``` -------------------------------- ### Set Boolean Options with url.Bool() Source: https://github.com/wangluozhe/requests/blob/main/README.md Shows how to explicitly set boolean options like Verify, AllowRedirects, and ForceHTTP1 using the url.Bool() helper function. Nil uses session defaults. ```go req.Verify = url.Bool(false) // 显式关闭 TLS 证书验证 req.AllowRedirects = url.Bool(false) // 显式禁用重定向 req.ForceHTTP1 = url.Bool(true) // 显式强制使用 HTTP/1 ``` -------------------------------- ### Get Response Text Content Source: https://github.com/wangluozhe/requests/blob/main/README.md Retrieve the response body as a string. Requests automatically decodes most common unicode character sets. ```go package main import ( "fmt" "github.com/wangluozhe/requests" ) func main() { r, err := requests.Get("https://api.github.com/events", nil) if err != nil { fmt.Println(err) } fmt.Println(r.Text()) } [{"repository":{"open_issues":0, "url":"https://github.com/"... ``` -------------------------------- ### Encoding Utilities - Hex, Base64, Base32, URI, Escape Source: https://context7.com/wangluozhe/requests/llms.txt Demonstrates various encoding and decoding functions including Hex, Base64 (btoa/atob compatible), Base32, URI encoding/decoding, and JavaScript-compatible escape/unescape. All functions accept string or []byte. ```go package main import ( "fmt" "github.com/wangluozhe/requests/utils" ) func main() { input := "https://example.com?name=你好&page=1" // Hex hexed := utils.HexEncode(input) fmt.Println("HexEncode:", string(hexed)) fmt.Println("HexDecode:", string(utils.HexDecode(hexed))) // Base64 (btoa/atob compatible) b64 := utils.Btoa(input) fmt.Println("Btoa:", b64) fmt.Println("Atob:", utils.Atob(b64)) // Base32 b32 := utils.Base32Encode(input) fmt.Println("Base32Encode:", b32) fmt.Println("Base32Decode:", utils.Base32Decode(b32)) // URI encoding encoded := utils.EncodeURIComponent(input) fmt.Println("EncodeURIComponent:", encoded) fmt.Println("DecodeURIComponent:", utils.DecodeURIComponent(encoded)) encoded2 := utils.EncodeURI(input) fmt.Println("EncodeURI:", encoded2) fmt.Println("DecodeURI:", utils.DecodeURI(encoded2)) // JavaScript escape/unescape (Unicode-style %uXXXX) esc := utils.Escape(input) fmt.Println("Escape:", esc) fmt.Println("UnEscape:", utils.UnEscape(esc)) } ``` -------------------------------- ### Send Other HTTP Requests (DELETE, HEAD, OPTIONS) Source: https://github.com/wangluozhe/requests/blob/main/README.md Illustrates the simple syntax for sending DELETE, HEAD, and OPTIONS requests. These follow the same pattern as POST requests. ```go data := url.NewData() data.Set("key","value") r, err := requests.Post("http://httpbin.org/post", &url.Request{Data: data}) r, err = requests.Delete("http://httpbin.org/delete") r, err = requests.Head("http://httpbin.org/get") r, err = requests.Options("http://httpbin.org/get") ``` -------------------------------- ### Send POST Request with Data Source: https://github.com/wangluozhe/requests/blob/main/README.md Demonstrates sending a POST request with form data. It initializes url.Data, sets key-value pairs, and then sends the request. ```go data := url.NewData() data.Set("key","value") r, err := requests.Post("http://httpbin.org/post", &url.Request{Data: data}) ``` -------------------------------- ### Base64 and Base32 Encoding/Decoding in Go Source: https://github.com/wangluozhe/requests/blob/main/README.md Demonstrates Base32 and Base64 encoding and decoding of a URL string using the requests library's utility functions. Also shows JavaScript-like btoa/atob equivalents. ```Go package main import ( "fmt" "github.com/wangluozhe/requests/utils" ) func main() { url := "https://www.baidu.com?page=10&abc=123&name=你好啊" base32en := utils.Base32Encode(url) fmt.Println(base32en) base32de := utils.Base32Decode(base32en) fmt.Println(base32de) base64en := utils.Base64Encode(url) fmt.Println(base64en) base64de := utils.Base64Decode(base64en) fmt.Println(base64de) // 或者像JavaScript语言一样 btoa := utils.Btoa(url) fmt.Println(btoa) atob := utils.Atob(btoa) fmt.Println(atob) } ``` -------------------------------- ### Disabling Redirects in Go Source: https://github.com/wangluozhe/requests/blob/main/README.md Shows how to disable automatic redirect handling for GET, OPTIONS, POST, PUT, PATCH, or DELETE requests by setting 'AllowRedirects' to false. ```go req := url.NewRequest() req.AllowRedirects = url.Bool(false) r, err := requests.Get("http://github.com", req) if err != nil { fmt.Println(err) } fmt.Println(r.StatusCode) 301 fmt.Println(r.History) [] ``` -------------------------------- ### Create a Persistent Session with requests.NewSession Source: https://context7.com/wangluozhe/requests/llms.txt Use NewSession to create a session that persists cookies, headers, proxies, and TLS configurations across multiple requests. Session-level settings are merged with per-request settings, with per-request values taking precedence. ```go package main import ( "fmt" "github.com/wangluozhe/requests" "github.com/wangluozhe/requests/url" "time" ) func main() { s := requests.NewSession() // Set session-level defaults s.Headers.Set("User-Agent", "MyBot/1.0") s.Timeout = 15 * time.Second s.Proxies = "http://127.0.0.1:8080" s.Verify = true // verify TLS certificates (default) // First request — session cookies are saved automatically r, err := s.Get("https://httpbin.org/cookies/set/session_id/abc123", nil) if err != nil { fmt.Println(err) return } fmt.Println("Status:", r.StatusCode) // Second request — session_id cookie is sent automatically r, err = s.Get("https://httpbin.org/cookies", nil) if err != nil { fmt.Println(err) return } fmt.Println("Cookies:", r.Text()) // {"cookies": {"session_id": "abc123"}} } ``` -------------------------------- ### Flexible Parameter Passing with map Source: https://github.com/wangluozhe/requests/blob/main/README.md Demonstrates passing query parameters and headers using map[string]string directly to the Request struct. The library automatically handles conversion. ```go import "github.com/wangluozhe/requests/url" req := &url.Request{ // 直接使用 map 传递查询参数 Params: map[string]string{ "page": "1", "size": "20", }, // 直接使用 map 传递 Header Headers: map[string]string{ "Authorization": "Bearer token123", }, // 直接传递字符串 Body Body: "raw body content", } ``` -------------------------------- ### Get Response Binary Content Source: https://github.com/wangluozhe/requests/blob/main/README.md Access the response body as a byte array. This is suitable for non-textual content like images. Requests automatically handles gzip, deflate, and br decompression. ```go fmt.Println(r.Content) [91 123 34 105 100 34 58 34 50 48 55 49 52 50 51 57 56 48 53 34 44 34 116 121 112 101 34 58 34... ``` -------------------------------- ### transport.ToHTTP2Settings Source: https://context7.com/wangluozhe/requests/llms.txt Converts an H2Settings struct into *http.HTTP2Settings for HTTP/2 fingerprint customization. This function controls SETTINGS frame values, WINDOW_UPDATE frames, header priority, and priority frames sent at connection start. ```APIDOC ## transport.ToHTTP2Settings — HTTP/2 fingerprint customization ### Description `transport.ToHTTP2Settings` converts an `H2Settings` struct into `*http.HTTP2Settings` controlling SETTINGS frame values, WINDOW_UPDATE frames, header priority, and priority frames sent at connection start. ### Usage Example ```go package main import ( "fmt" "github.com/wangluozhe/requests" "github.com/wangluozhe/requests/transport" "github.com/wangluozhe/requests/url" ) func main() { req := url.NewRequest() req.Ja3 = "771,4865-4866-4867-49195-49199-49196-49200-52393-52392-49171-49172-156-157-47-53,0-23-65281-10-11-35-16-5-13-18-51-45-43-27-21,29-23-24,0" h2s := &transport.H2Settings{ Settings: map[string]int{ "HEADER_TABLE_SIZE": 65536, "INITIAL_WINDOW_SIZE": 131072, "MAX_FRAME_SIZE": 16384, }, SettingsOrder: []string{ "HEADER_TABLE_SIZE", "INITIAL_WINDOW_SIZE", "MAX_FRAME_SIZE", }, ConnectionFlow: 12517377, HeaderPriority: map[string]interface{}{ "weight": 42, "streamDep": 13, "exclusive": false, }, } req.HTTP2Settings = transport.ToHTTP2Settings(h2s) r, err := requests.Get("https://tls.peet.ws/api/all", req) if err != nil { fmt.Println(err) return } fmt.Println(r.Text()) } ``` ``` -------------------------------- ### HTTP Basic Authentication with requests Source: https://context7.com/wangluozhe/requests/llms.txt Enable HTTP Basic Authentication by setting `req.Auth` to a `[]string{"username", "password"}` slice. Session-level authentication overrides per-request settings. ```go package main import ( "fmt" "github.com/wangluozhe/requests" "github.com/wangluozhe/requests/url" ) func main() { req := url.NewRequest() req.Auth = []string{"user", "password"} r, err := requests.Get("https://httpbin.org/basic-auth/user/password", req) if err != nil { fmt.Println(err) return } fmt.Println("Status:", r.StatusCode) // 200 fmt.Println(r.Text()) // {"authenticated": true, "user": "user"} // Session-level auth s := requests.NewSession() s.Auth = []string{"admin", "secret"} r2, _ := s.Get("https://httpbin.org/basic-auth/admin/secret", nil) fmt.Println("Session auth:", r2.StatusCode) } ``` -------------------------------- ### Generate SHA Series Hashes Source: https://github.com/wangluozhe/requests/blob/main/README.md Shows how to calculate SHA1, SHA224, SHA256, SHA384, and SHA512 hashes and encode them into base64 and hexadecimal formats. Requires importing 'github.com/wangluozhe/requests/utils'. ```go package main import ( "fmt" "github.com/wangluozhe/requests/utils" ) func main() { s1 := utils.SHA1("123") b64 := utils.Btoa(s1) h16 := utils.HexEncode(s1) fmt.Println("SHA1-base64:", b64) fmt.Println("SHA1-hex:", string(h16)) s2 := utils.SHA224("123") b64 = utils.Btoa(s2) h16 = utils.HexEncode(s2) fmt.Println("SHA224-base64:", b64) fmt.Println("SHA224-hex:", string(h16)) s2 = utils.SHA256("123") b64 = utils.Btoa(s2) h16 = utils.HexEncode(s2) fmt.Println("SHA256-base64:", b64) fmt.Println("SHA256-hex:", string(h16)) s5 := utils.SHA384("123") b64 = utils.Btoa(s5) h16 = utils.HexEncode(s5) fmt.Println("SHA384-base64:", b64) fmt.Println("SHA384-hex:", string(h16)) s5 = utils.SHA512("123") b64 = utils.Btoa(s5) h16 = utils.HexEncode(s5) fmt.Println("SHA512-base64:", b64) fmt.Println("SHA512-hex:", string(h16)) } ``` -------------------------------- ### HTTP/HTTPS proxy configuration Source: https://context7.com/wangluozhe/requests/llms.txt Explains how to configure proxy servers for requests using the `Proxies` field on `url.Request` or `requests.Session`, including support for authentication. ```APIDOC ## Proxies — HTTP/HTTPS proxy configuration Set `req.Proxies` or `session.Proxies` to route requests through a proxy server. Supports HTTP and HTTPS proxies with optional authentication. ```go package main import ( "fmt" "github.com/wangluozhe/requests" "github.com/wangluozhe/requests/url" ) func main() { // Per-request proxy req := url.NewRequest() req.Proxies = "http://127.0.0.1:8080" req.Verify = url.Bool(false) // often needed with local intercepting proxies r, err := requests.Get("https://httpbin.org/get", req) if err != nil { fmt.Println(err) return } fmt.Println("Status:", r.StatusCode) // Proxy with credentials req2 := url.NewRequest() req2.Proxies = "http://proxyuser:proxypass@proxy.example.com:3128" r2, err := requests.Get("https://httpbin.org/get", req2) if err != nil { fmt.Println(err) return } fmt.Println("Status:", r2.StatusCode) // Session-level proxy (applies to all requests in session) s := requests.NewSession() s.Proxies = "http://127.0.0.1:8888" r3, _ := s.Get("https://httpbin.org/ip", nil) fmt.Println(r3.Text()) } ``` ``` -------------------------------- ### Generate MD Series Hashes Source: https://github.com/wangluozhe/requests/blob/main/README.md Demonstrates how to compute MD4, RIPEMD160, and MD5 hashes for a given string. Ensure the 'github.com/wangluozhe/requests/utils' package is imported. ```go package main import ( "fmt" "github.com/wangluozhe/requests/utils" ) func main() { m := utils.MD4("123") fmt.Println("MD4:", m) m = utils.RIPEMD160("123") fmt.Println("RIPEMD160:", m) m = utils.MD5("123") fmt.Println("MD5:", m) } ``` -------------------------------- ### Setting Request Timeout in Go Source: https://github.com/wangluozhe/requests/blob/main/README.md Explains how to set a timeout for a request using the 'Timeout' parameter. If the server does not respond within the specified duration, an error will occur. Note that this timeout applies to the connection phase, not the entire download. ```go req := url.NewRequest() req.Timeout = 1 * time.Millisecond r, err := requests.Get("http://github.com",req) if err != nil { fmt.Println(err) } panic: runtime error: invalid memory address or nil pointer dereference [signal 0xc0000005 code=0x0 addr=0x0 pc=0x253460] goroutine 1 [running]: main.main() D:/Go/github.com/wangluozhe/requests/examples/test.go:27 +0xc0 ``` -------------------------------- ### Pass URL Parameters with String Source: https://github.com/wangluozhe/requests/blob/main/README.md Construct URL parameters directly from a query string. This method is straightforward for simple parameter sets. ```go params := url.ParseParams("key1=value1&key2=value2") r, err := requests.Get("http://httpbin.org/get",&url.Request{Params: params}) if err != nil { fmt.Println(err) } ``` -------------------------------- ### Verify URL Encoding of Parameters Source: https://github.com/wangluozhe/requests/blob/main/README.md Print the final URL after making a request with parameters to verify that the query string has been correctly encoded. ```go fmt.Println(r.Url) http://httpbin.org/get?key1=value1&key2=value2 ``` -------------------------------- ### requests.Put / requests.Patch / requests.Delete / requests.Head / requests.Options / requests.Connect / requests.Trace Source: https://context7.com/wangluozhe/requests/llms.txt Convenience functions for various HTTP methods (PUT, PATCH, DELETE, HEAD, OPTIONS, CONNECT, TRACE). They all share the same signature and accept an optional `url.Request` object for configuration. ```APIDOC ## requests.Put / requests.Patch / requests.Delete — Other HTTP methods Convenience functions for PUT, PATCH, DELETE, HEAD, OPTIONS, CONNECT, and TRACE requests, all accepting the same `(rawurl string, req *url.Request)` signature. ### Method PUT, PATCH, DELETE, HEAD, OPTIONS, CONNECT, TRACE ### Endpoint (URL provided in the function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **Json** (map[string]interface{}) - For sending JSON payloads (applicable to methods like PUT, PATCH). - **Data** (map[string]string) - For sending form-encoded data (applicable to methods like PUT, PATCH). - (Other fields in `url.Request` can configure request details) ### Request Example ```go package main import ( "fmt" "github.com/wangluozhe/requests" "github.com/wangluozhe/requests/url" ) func main() { // PUT request with JSON req := url.NewRequest() req.Json = map[string]interface{}{"status": "active"} r, err := requests.Put("https://httpbin.org/put", req) if err != nil { fmt.Println(err) return } fmt.Println("PUT status:", r.StatusCode) // DELETE request r, err = requests.Delete("https://httpbin.org/delete", nil) if err != nil { fmt.Println(err) return } fmt.Println("DELETE status:", r.StatusCode) // HEAD request (redirects disabled automatically) r, err = requests.Head("https://httpbin.org/get", nil) if err != nil { fmt.Println(err) return } fmt.Println("HEAD Content-Type:", r.Headers.Get("Content-Type")) } ``` ### Response #### Success Response (200) - **StatusCode** (int) - The HTTP status code of the response. - **Headers** (map[string][]string) - The response headers. - **Text()** (string) - Returns the response body as a string (for methods that return a body). ``` -------------------------------- ### Multipart File Upload and Form Data Source: https://context7.com/wangluozhe/requests/llms.txt Use url.NewFiles() to build multipart/form-data bodies. Attach files with SetFile() and add text fields with SetField(). ```go package main import ( "fmt" "github.com/wangluozhe/requests" "github.com/wangluozhe/requests/url" ) func main() { files := url.NewFiles() // Attach a file: SetFile(fieldName, fileName, filePath, contentType) files.SetFile("avatar", "profile.png", "/tmp/profile.png", "image/png") // Add plain text fields alongside the file files.SetField("username", "alice") files.SetField("description", "Hello world") req := url.NewRequest() req.Files = files r, err := requests.Post("https://httpbin.org/post", req) if err != nil { fmt.Println(err) return } fmt.Println("Status:", r.StatusCode) fmt.Println(r.Text()) // Response shows "files": {"avatar": "..."} and "form": {"username": "alice", ...} } ``` -------------------------------- ### Register Middleware with Session.Use Source: https://context7.com/wangluozhe/requests/llms.txt Register middleware functions using Session.Use to intercept and modify requests or responses. Middlewares follow the onion model and execute in registration order, useful for logging, authentication, or retry logic. ```go package main import ( "log" "time" "github.com/wangluozhe/requests" "github.com/wangluozhe/requests/models" "github.com/wangluozhe/requests/url" ) func LoggingMiddleware(next requests.Handler) requests.Handler { return func(preq *models.PrepareRequest, req *url.Request) (*models.Response, error) { start := time.Now() log.Printf("→ %s %s", preq.Method, preq.Url) resp, err := next(preq, req) log.Printf("← %s %s [%dms]", preq.Method, preq.Url, time.Since(start).Milliseconds()) return resp, err } } func AuthMiddleware(token string) requests.Middleware { return func(next requests.Handler) requests.Handler { return func(preq *models.PrepareRequest, req *url.Request) (*models.Response, error) { preq.Headers.Set("Authorization", "Bearer "+token) return next(preq, req) } } } func main() { s := requests.NewSession() s.Use(LoggingMiddleware) s.Use(AuthMiddleware("my-secret-token")) r, err := s.Get("https://httpbin.org/headers", nil) if err != nil { panic(err) } fmt.Println(r.Text()) // Output includes Authorization: Bearer my-secret-token } ``` -------------------------------- ### Configuring HTTP/HTTPS Proxies Source: https://context7.com/wangluozhe/requests/llms.txt Route requests through a proxy server by setting `req.Proxies` or `session.Proxies`. Supports HTTP/HTTPS proxies and optional authentication credentials. ```go package main import ( "fmt" "github.com/wangluozhe/requests" "github.com/wangluozhe/requests/url" ) func main() { // Per-request proxy req := url.NewRequest() req.Proxies = "http://127.0.0.1:8080" req.Verify = url.Bool(false) // often needed with local intercepting proxies r, err := requests.Get("https://httpbin.org/get", req) if err != nil { fmt.Println(err) return } fmt.Println("Status:", r.StatusCode) // Proxy with credentials req2 := url.NewRequest() req2.Proxies = "http://proxyuser:proxypass@proxy.example.com:3128" r2, err := requests.Get("https://httpbin.org/get", req2) if err != nil { fmt.Println(err) return } fmt.Println("Status:", r2.StatusCode) // Session-level proxy (applies to all requests in session) s := requests.NewSession() s.Proxies = "http://127.0.0.1:8888" r3, _ := s.Get("https://httpbin.org/ip", nil) fmt.Println(r3.Text()) } ``` -------------------------------- ### Pass Multiple Values for a Parameter Source: https://github.com/wangluozhe/requests/blob/main/README.md When a URL parameter needs to accept multiple values, use `Add` to append values to an existing key. `Set` will overwrite existing values. ```go params := url.NewParams() params.Set("key1","value1") params.Add("key1","value2") params.Set("key2","value2") r, err := requests.Get("http://httpbin.org/get",&url.Request{Params: params}) if err != nil { fmt.Println(err) } fmt.Println(r.Url) http://httpbin.org/post?key1=value1&key1=value2&key2=value2 ``` -------------------------------- ### Build and Parse URL Query Parameters Source: https://context7.com/wangluozhe/requests/llms.txt Use url.NewParams() to build query parameters programmatically, supporting multiple values for the same key. Parse parameters from maps using url.ParseParams(). ```go package main import ( "fmt" "github.com/wangluozhe/requests" "github.com/wangluozhe/requests/url" ) func main() { // Build params programmatically params := url.NewParams() params.Set("category", "books") params.Add("tag", "fiction") params.Add("tag", "history") // multiple values for same key params.Set("page", "2") r, err := requests.Get("https://httpbin.org/get", &url.Request{Params: params}) if err != nil { fmt.Println(err) return } fmt.Println("URL:", r.Url) // https://httpbin.org/get?category=books&tag=fiction&tag=history&page=2 // Parse from a map req := url.NewRequest() req.Params = url.ParseParams(map[string]interface{}{ "ids": []int{1, 2, 3}, "sort": "asc", }) r, _ = requests.Get("https://httpbin.org/get", req) fmt.Println("URL:", r.Url) // https://httpbin.org/get?ids=1&ids=2&ids=3&sort=asc } ``` -------------------------------- ### Customize HTTP/2 Settings with transport.ToHTTP2Settings Source: https://context7.com/wangluozhe/requests/llms.txt Converts an `H2Settings` struct into `*http.HTTP2Settings` to control SETTINGS frame values, WINDOW_UPDATE frames, and header priority. Use this for HTTP/2 fingerprint customization. ```go package main import ( "fmt" "github.com/wangluozhe/requests" "github.com/wangluozhe/requests/transport" "github.com/wangluozhe/requests/url" ) func main() { req := url.NewRequest() req.Ja3 = "771,4865-4866-4867-49195-49199-49196-49200-52393-52392-49171-49172-156-157-47-53,0-23-65281-10-11-35-16-5-13-18-51-45-43-27-21,29-23-24,0" h2s := &transport.H2Settings{ Settings: map[string]int{ "HEADER_TABLE_SIZE": 65536, "INITIAL_WINDOW_SIZE": 131072, "MAX_FRAME_SIZE": 16384, }, SettingsOrder: []string{ "HEADER_TABLE_SIZE", "INITIAL_WINDOW_SIZE", "MAX_FRAME_SIZE", }, ConnectionFlow: 12517377, HeaderPriority: map[string]interface{}{ "weight": 42, "streamDep": 13, "exclusive": false, }, } req.HTTP2Settings = transport.ToHTTP2Settings(h2s) r, err := requests.Get("https://tls.peet.ws/api/all", req) if err != nil { fmt.Println(err) return } fmt.Println(r.Text()) } ``` -------------------------------- ### Configure Per-Request Settings with url.Request Source: https://context7.com/wangluozhe/requests/llms.txt Configure individual requests using the url.Request struct, which accepts flexible types for parameters, headers, cookies, and body. Use url.Bool(v) for boolean fields like Verify and AllowRedirects to distinguish unset from explicit false. ```go package main import ( "fmt" "time" "github.com/wangluozhe/requests" "github.com/wangluozhe/requests/url" ) func main() { req := &url.Request{ // Query parameters — accepts map, string, or *url.Params Params: map[string]string{"q": "golang", "page": "1"}, // Headers — accepts map, multiline string, or *http.Header Headers: map[string]string{ "User-Agent": "Mozilla/5.0", "Accept": "application/json", }, // Cookies — accepts string, map, or *cookiejar.Jar Cookies: "session=abc; token=xyz", // JSON body Json: map[string]interface{}{"key": "value"}, // Timeout for this request only Timeout: 10 * time.Second, // Disable TLS certificate verification for this request Verify: url.Bool(false), // Disable automatic redirect following AllowRedirects: url.Bool(false), // Proxy for this request only Proxies: "http://user:pass@proxy.example.com:3128", } r, err := requests.Get("https://httpbin.org/get", req) if err != nil { fmt.Println("Error:", err) return } fmt.Println(r.StatusCode, r.Text()) } ``` -------------------------------- ### Session.Use Source: https://context7.com/wangluozhe/requests/llms.txt Registers one or more middleware functions to the session. Middlewares are executed in the order they are registered and can be used for tasks like logging, authentication, or retry logic. ```APIDOC ## Session.Use — Register middleware `Session.Use` registers one or more middleware functions. Middlewares follow the onion model: they wrap the final `Send` handler and execute in registration order. Useful for logging, authentication token injection, and retry logic. ```go package main import ( "log" "time" "github.com/wangluozhe/requests" "github.com/wangluozhe/requests/models" "github.com/wangluozhe/requests/url" ) func LoggingMiddleware(next requests.Handler) requests.Handler { return func(preq *models.PrepareRequest, req *url.Request) (*models.Response, error) { start := time.Now() log.Printf("→ %s %s", preq.Method, preq.Url) resp, err := next(preq, req) log.Printf("← %s %s [%dms]", preq.Method, preq.Url, time.Since(start).Milliseconds()) return resp, err } } func AuthMiddleware(token string) requests.Middleware { return func(next requests.Handler) requests.Handler { return func(preq *models.PrepareRequest, req *url.Request) (*models.Response, error) { preq.Headers.Set("Authorization", "Bearer "+token) return next(preq, req) } } } func main() { s := requests.NewSession() s.Use(LoggingMiddleware) s.Use(AuthMiddleware("my-secret-token")) r, err := s.Get("https://httpbin.org/headers", nil) if err != nil { panic(err) } fmt.Println(r.Text()) // Output includes Authorization: Bearer my-secret-token } ``` ``` -------------------------------- ### URI Encode and Decode URL Components Source: https://github.com/wangluozhe/requests/blob/main/README.md This snippet demonstrates URI encoding and decoding using `EncodeURIComponent`, `DecodeURIComponent`, `EncodeURI`, `DecodeURI`, `Escape`, and `UnEscape` from the `requests/utils` package. It shows how to handle special characters and non-ASCII characters in URLs. ```Go package main import ( "fmt" "github.com/wangluozhe/requests/utils" ) func main() { url := "https://www.baidu.com?page=10&abc=123&name=你好啊" encode := utils.EncodeURIComponent(url) fmt.Println(encode) decode := utils.DecodeURIComponent(encode) fmt.Println(decode) encode1 := utils.EncodeURI(url) fmt.Println(encode1) decode1 := utils.DecodeURI(encode1) fmt.Println(decode1) escape := utils.Escape(url) fmt.Println(escape) unescape := utils.UnEscape(escape) fmt.Println(unescape) } ``` -------------------------------- ### Client Certificates for Mutual TLS (mTLS) Source: https://context7.com/wangluozhe/requests/llms.txt Authenticate the client using a certificate by setting `req.Cert` or `session.Cert`. Provide a `[]string` with certificate and key file paths. A 3-element slice can include a root CA path. ```go package main import ( "fmt" "github.com/wangluozhe/requests" "github.com/wangluozhe/requests/url" ) func main() { req := url.NewRequest() // 2-element: [certPEM, keyPEM] req.Cert = []string{"/path/to/client.crt", "/path/to/client.key"} r, err := requests.Get("https://mtls.example.com/api", req) if err != nil { fmt.Println(err) return } fmt.Println("Status:", r.StatusCode) // 3-element: [certPEM, keyPEM, rootCA] req2 := url.NewRequest() req2.Cert = []string{"client.crt", "client.key", "rootca.crt"} r2, err := requests.Get("https://mtls.example.com/api", req2) if err != nil { fmt.Println(err) return } fmt.Println("mTLS Status:", r2.StatusCode) } ``` -------------------------------- ### Accessing Response Headers in Go Source: https://github.com/wangluozhe/requests/blob/main/README.md Demonstrates how to view and access server response headers, which are provided as an http.Header type (map[string][]string). Headers are case-insensitive. ```go fmt.Println(r.Headers) map[Access-Control-Allow-Credentials:[true] Access-Control-Allow-Origin:[*] Connection:[keep-alive] Content-Length:[1976] Content-Type:[application/json] Date:[Sat, 12 Mar 2022 15:59:05 GMT] Server:[gunicorn/19.9.0]] ``` ```go fmt.Println(r.Headers["Content-Type"][0]) application/json ``` ```go fmt.Println(r.Headers.Get("content-type")) application/json ``` -------------------------------- ### POST FormData Source: https://github.com/wangluozhe/requests/blob/main/README.md Send FormData using the Files parameter. Use SetField() to specify the field name and value. ```Go files := url.NewFiles() // SetFile(name,value) // name为字段名,value为值 files.SetField("name","value") req := url.NewRequest() req.Files = files r, err := requests.Post("http://httpbin.org/post",req) if err != nil { fmt.Println(err) } fmt.Println(r.Text()) ``` -------------------------------- ### Manage HTTP Request Headers Source: https://context7.com/wangluozhe/requests/llms.txt Use url.ParseHeaders() to parse headers from a multiline string, respecting default HTTP/2 pseudo-header order. Control wire transmission order using the "Header-Order:" key. ```go package main import ( "fmt" "github.com/wangluozhe/requests" "github.com/wangluozhe/requests/url" http "github.com/wangluozhe/chttp" ) func main() { // Ordered headers using ParseHeaders with a multiline string req := url.NewRequest() req.Headers = url.ParseHeaders(` user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0.0.0 Safari/537.36 accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 accept-language: en-US,en;q=0.9 accept-encoding: gzip, deflate, br `) r, err := requests.Get("https://httpbin.org/headers", req) if err != nil { fmt.Println(err) return } fmt.Println(r.Text()) // Explicitly ordered headers via Header-Order key headers := url.NewHeaders() headers.Set("User-Agent", "MyApp/1.0") headers.Set("Accept", "application/json") headers.Set("X-Custom", "value") (*headers)[http.HeaderOrderKey] = []string{"user-agent", "x-custom", "accept"} req2 := url.NewRequest() req2.Headers = headers r2, _ := requests.Get("https://httpbin.org/headers", req2) fmt.Println(r2.Text()) } ``` -------------------------------- ### Hash Utilities - MD, SHA, HMAC Source: https://context7.com/wangluozhe/requests/llms.txt Provides hashing functions including MD4, RIPEMD160, MD5 (returning hex strings), and SHA1/224/256/384/512 (returning []byte). HMAC variants are also available for all listed algorithms. ```go package main import ( "fmt" "github.com/wangluozhe/requests/utils" ) func main() { data := "hello world" key := "secret-key" // MD family (returns hex string) fmt.Println("MD5:", utils.MD5(data)) // 5eb63bbbe01eeed093cb22bb8f5acdc3 fmt.Println("MD4:", utils.MD4(data)) fmt.Println("RIPEMD160:", utils.RIPEMD160(data)) // SHA family (returns []byte — encode as needed) sha256raw := utils.SHA256(data) fmt.Println("SHA256-hex:", string(utils.HexEncode(sha256raw))) fmt.Println("SHA256-b64:", utils.Btoa(sha256raw)) fmt.Println("SHA1-hex: ", string(utils.HexEncode(utils.SHA1(data)))) fmt.Println("SHA512-hex:", string(utils.HexEncode(utils.SHA512(data)))) // HMAC family (returns []byte) hmac256 := utils.HmacSHA256(data, key) fmt.Println("HmacSHA256-hex:", string(utils.HexEncode(hmac256))) fmt.Println("HmacSHA256-b64:", utils.Btoa(hmac256)) hmacMD5 := utils.HmacMD5(data, key) fmt.Println("HmacMD5-hex:", string(utils.HexEncode(hmacMD5))) hmacSHA1 := utils.HmacSHA1(data, key) fmt.Println("HmacSHA1-hex:", string(utils.HexEncode(hmacSHA1))) } ``` -------------------------------- ### Accessing Response Cookies in Go Source: https://github.com/wangluozhe/requests/blob/main/README.md Shows how to access cookies from an HTTP response. The 'Cookies' field provides a list of cookies. ```go url := "https://www.baidu.com" r, err := requests.Get(url, nil) fmt.Println(r.Cookies) [BD_NOT_HTTPS=1; Path=/; Max-Age=300 BIDUPSID=7DB59A8D47E763943295969C33979837; Path=/; Domain=baidu.com; Max-Age=2147483647 PSTM=1647233990; Path=/; Domain=baidu.com; Max-Age=2147483647 BAIDUID=7DB59A8D47E7639495833AF6370F9985:FG=1; Path=/; Domain=baidu.com; Max-Age=31536000] ``` -------------------------------- ### Hex Encode and Decode URL Source: https://github.com/wangluozhe/requests/blob/main/README.md This snippet shows how to use the `HexEncode` and `HexDecode` functions from the `requests/utils` package to convert a URL string to its hexadecimal representation and back. It handles byte slices for encoding and decoding. ```Go package main import ( "fmt" "github.com/wangluozhe/requests/utils" ) func main() { url := "https://www.baidu.com" hexen := utils.HexEncode(url) fmt.Println(hexen) fmt.Println(string(hexen)) hexde := utils.HexDecode(hexen) fmt.Println(hexde) fmt.Println(string(hexde)) } ``` -------------------------------- ### Pass URL Parameters with Dictionary Source: https://github.com/wangluozhe/requests/blob/main/README.md Use the `params` keyword argument with a dictionary to pass data to the URL's query string. This is useful for constructing URLs with key-value pairs. ```go params := url.NewParams() params.Set("key1","value1") params.Set("key2","value2") r, err := requests.Get("http://httpbin.org/get",&url.Request{Params: params}) if err != nil { fmt.Println(err) } ```