### Create Basic HTTP Client with Custom Configuration in Go Source: https://context7.com/sicko7947/psychoclient/llms.txt Demonstrates how to create a basic `Client` in Go using PsychoClient. This client is configured for custom TLS fingerprinting, disables redirect following, sets a timeout, and specifies an authenticated proxy. It then makes a GET request to a specified endpoint and prints the response status and body. Dependencies include the psychoclient library. ```go package main import ( "fmt" "strings" "time" "github.com/sicko7947/psychoclient" ) func main() { // Create a new client with custom configuration client := psychoclient.NewClient(&psychoclient.SessionBuilder{ UseDefaultClient: false, // Use custom TLS fingerprinting FollowRedirects: false, // Don't follow redirects Timeout: 30 * time.Second, Proxy: "http://user:pass@proxy.example.com:8080", }) // Build a request headers := map[string]string{ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", } resp, body, err := client.DoNewRequest(&psychoclient.RequestBuilder{ Endpoint: "https://example.com/api/endpoint", Method: "GET", Headers: headers, Payload: nil, }) if err != nil { fmt.Printf("Request failed: %v\n", err) return } fmt.Printf("Status: %d\n", resp.StatusCode) fmt.Printf("Body: %s\n", string(body)) // Output: Status: 200 // Body: {"success": true} } ``` -------------------------------- ### Configure HTTP/HTTPS Proxies with Authentication in Go Source: https://context7.com/sicko7947/psychoclient/llms.txt Demonstrates how to configure and use HTTP/HTTPS proxies, including those with authentication, using the psychoclient library in Go. It shows examples of simple, authenticated, and HTTPS proxies, and how to perform requests through them. The library supports various proxy URL formats and automatic CONNECT tunneling for HTTPS. ```go package main import ( "fmt" "time" "github.com/sicko7947/psychoclient" ) func main() { // Simple HTTP proxy simpleProxy := psychoclient.NewClient(&psychoclient.SessionBuilder{ UseDefaultClient: false, Proxy: "http://proxy.example.com:8080", Timeout: 30 * time.Second, }) // Authenticated proxy with credentials authProxy := psychoclient.NewClient(&psychoclient.SessionBuilder{ UseDefaultClient: false, Proxy: "http://username:password@secure-proxy.com:3128", Timeout: 30 * time.Second, }) // HTTPS proxy with authentication httpsProxy := psychoclient.NewClient(&psychoclient.SessionBuilder{ UseDefaultClient: false, Proxy: "https://user:pass@proxy.example.com:443", Timeout: 30 * time.Second, }) // Test request through proxy resp, _, err := authProxy.DoNewRequest(&psychoclient.RequestBuilder{ Endpoint: "https://api.ipify.org?format=json", Method: "GET", Headers: map[string]string{"Accept": "application/json"}, }) if err != nil { fmt.Printf("Proxy request failed: %v\n", err) return } fmt.Printf("Request through proxy: %d\n", resp.StatusCode) // Proxy format supports: // - http://ip:port // - http://username:password@ip:port // - https://username:password@ip:port // - Automatic CONNECT tunneling for HTTPS targets // - HTTP/2 proxy connection reuse // Output: Request through proxy: 200 } ``` -------------------------------- ### Create and Use Stateful Sessions with Cookie Management in Go Source: https://context7.com/sicko7947/psychoclient/llms.txt Illustrates the creation and usage of a stateful `Session` in Go with PsychoClient. This session manages cookies automatically, allows request queueing, and supports chained requests where cookies from one request are used in subsequent ones. It demonstrates logging in, retrieving a session cookie, and making an authenticated API call. The session is closed using `defer`. Dependencies include the psychoclient library. ```go package main import ( "fmt" "strings" "time" "github.com/sicko7947/psychoclient" ) func main() { // Create a new session session, err := psychoclient.NewSession(&psychoclient.SessionBuilder{ UseDefaultClient: false, FollowRedirects: true, Timeout: 30 * time.Second, Proxy: "", // No proxy }) if err != nil { panic(err) } defer session.Close() // Build and queue first request (login) reqID1, _ := session.BuildRequest(&psychoclient.RequestBuilder{ Endpoint: "https://api.example.com/login", Method: "POST", Headers: map[string]string{ "Content-Type": "application/json", }, Payload: strings.NewReader(`{"username":"user","password":"pass"}`), }) // Execute login request resp1, body1, err := session.Do(reqID1) // Request auto-removed after execution if err != nil { panic(err) } fmt.Printf("Login status: %d\n", resp1.StatusCode) // Cookies from login are automatically stored in session cookie, exists := session.GetCookie("session_token") if exists { fmt.Printf("Session cookie: %s\n", cookie.Value) } // Build second request (authenticated API call) // Cookies are automatically included from session reqID2, _ := session.BuildRequest(&psychoclient.RequestBuilder{ Endpoint: "https://api.example.com/user/profile", Method: "GET", Headers: map[string]string{ "Accept": "application/json", }, Payload: nil, }) // Execute with request reuse (false = keep request in queue) resp2, body2, err := session.Do(reqID2, false) if err != nil { panic(err) } fmt.Printf("Profile: %s\n", string(body2)) // Can reuse same request ID multiple times when false flag is used resp3, _, _ := session.Do(reqID2, false) fmt.Printf("Second call status: %d\n", resp3.StatusCode) // Clean up specific request session.RemoveRequest(reqID2) // Output: Login status: 200 // Session cookie: abc123xyz // Profile: {"name":"John Doe","email":"john@example.com"} // Second call status: 200 } ``` -------------------------------- ### Implement Error Handling and Connection Management in Go Source: https://context7.com/sicko7947/psychoclient/llms.txt Illustrates robust error handling and connection lifecycle management for production use with psychoclient. This Go code snippet shows how to create a session, build requests, execute them, and handle potential network errors, timeouts, and HTTP status code errors. It emphasizes the importance of deferring session closure to release resources. ```go package main import ( "errors" "fmt" "net" "time" "github.com/sicko7947/psychoclient" ) func main() { session, err := psychoclient.NewSession(&psychoclient.SessionBuilder{ UseDefaultClient: false, FollowRedirects: false, Timeout: 5 * time.Second, Proxy: "http://proxy.example.com:8080", }) if err != nil { panic(fmt.Sprintf("Session creation failed: %v", err)) } defer session.Close() // Always close to release connections reqID, err := session.BuildRequest(&psychoclient.RequestBuilder{ Endpoint: "https://example.com/api", Method: "POST", Headers: map[string]string{"Content-Type": "application/json"}, Payload: nil, }) if err != nil { panic(fmt.Sprintf("Request build failed: %v", err)) } resp, body, err := session.Do(reqID) // Handle various error types if err != nil { var netErr net.Error if errors.As(err, &netErr) && netErr.Timeout() { fmt.Println("Request timed out - retrying with longer timeout") session.Close() // Create new session with longer timeout session, _ = psychoclient.NewSession(&psychoclient.SessionBuilder{ UseDefaultClient: false, Timeout: 30 * time.Second, }) defer session.Close() reqID, _ = session.BuildRequest(&psychoclient.RequestBuilder{ Endpoint: "https://example.com/api", Method: "POST", }) resp, body, err = session.Do(reqID) } else { fmt.Printf("Request failed: %v\n", err) return } } if resp != nil { if resp.StatusCode >= 400 { fmt.Printf("HTTP error %d: %s\n", resp.StatusCode, string(body)) return } fmt.Printf("Success: %d\n", resp.StatusCode) } // Session.Close() ensures: // - All cookies cleared // - Request queue cleared // - Idle connections closed // - Resources released // Output: Success: 200 } ``` -------------------------------- ### Efficient Session Reuse with Go Session Pools Source: https://context7.com/sicko7947/psychoclient/llms.txt Explains how to use `SessionPool` for efficient reuse of HTTP sessions across concurrent operations, which is beneficial for tasks like botting or scraping with multiple proxies. It covers creating a pool, populating it with pre-configured sessions (including proxies), and managing session acquisition and release by worker goroutines. ```go package main import ( "fmt" "sync" "time" "github.com/sicko7947/psychoclient" ) func main() { // Create session pool with capacity of 5 pool := psychoclient.NewPool(5) defer pool.Close() // Populate pool with pre-configured sessions proxies := []string{ "http://user:pass@proxy1.com:8080", "http://user:pass@proxy2.com:8080", "http://user:pass@proxy3.com:8080", } for _, proxy := range proxies { session, err := psychoclient.NewSession(&psychoclient.SessionBuilder{ UseDefaultClient: false, FollowRedirects: false, Timeout: 15 * time.Second, Proxy: proxy, }) if err != nil { continue } pool.Push(session) } fmt.Printf("Pool size: %d\n", pool.Size()) // Worker function using pool worker := func(id int, wg *sync.WaitGroup) { defer wg.Done() // Get session from pool (blocks if empty) session := pool.Pop() if session == nil { fmt.Printf("Worker %d: no session available\n", id) return } // Use session for request reqID, _ := session.BuildRequest(&psychoclient.RequestBuilder{ Endpoint: fmt.Sprintf("https://api.example.com/item/%d", id), Method: "GET", Headers: map[string]string{"User-Agent": "Bot/1.0"}, }) resp, _, err := session.Do(reqID) if err != nil { fmt.Printf("Worker %d: request failed: %v\n", id, err) // Session failed, don't return to pool session.Close() return } fmt.Printf("Worker %d: status %d\n", id, resp.StatusCode) // Return session to pool for reuse pool.Push(session) } // Spawn 10 concurrent workers sharing 3 sessions var wg sync.WaitGroup for i := 1; i <= 10; i++ { wg.Add(1) go worker(i, &wg) } wg.Wait() fmt.Printf("Final pool size: %d\n", pool.Size()) // Output: Pool size: 3 // Worker 1: status 200 // Worker 2: status 200 // Worker 3: status 200 // ... // Final pool size: 3 } ``` -------------------------------- ### Go: Perform Low-Level HTTP RoundTrip Request Source: https://context7.com/sicko7947/psychoclient/llms.txt This Go code snippet demonstrates how to use the `RoundTrip` method of the psychoclient's `Session` to bypass client-level logic like redirect handling. It shows how to manually build a request, execute it at the transport layer, and manually check and follow redirects if necessary. This is useful for fine-grained control over network requests. ```go package main import ( "fmt" "time" "github.com/sicko7947/psychoclient" ) func main() { session, _ := psychoclient.NewSession(&psychoclient.SessionBuilder{ UseDefaultClient: false, FollowRedirects: false, Timeout: 10 * time.Second, }) defer session.Close() // Build request reqID, _ := session.BuildRequest(&psychoclient.RequestBuilder{ Endpoint: "https://example.com/redirect", Method: "GET", Headers: map[string]string{"User-Agent": "Custom/1.0"}, }) // RoundTrip executes at transport layer - no redirect following // even if session was configured to follow redirects resp, body, err := session.RoundTrip(reqID) if err != nil { panic(err) } // Check for redirect manually if resp.StatusCode >= 300 && resp.StatusCode < 400 { location := resp.Header.Get("Location") fmt.Printf("Redirect to: %s\n", location) // Manually follow redirect with new request reqID2, _ := session.BuildRequest(&psychoclient.RequestBuilder{ Endpoint: location, Method: "GET", Headers: map[string]string{"User-Agent": "Custom/1.0"}, }) resp, body, err = session.RoundTrip(reqID2) if err != nil { panic(err) } } fmt.Printf("Final status: %d\n", resp.StatusCode) fmt.Printf("Body length: %d bytes\n", len(body)) // Output: Redirect to: https://example.com/final // Final status: 200 // Body length: 1234 bytes } ``` -------------------------------- ### Manage HTTP Session Cookies with Go Source: https://context7.com/sicko7947/psychoclient/llms.txt Demonstrates how to manage cookies within an HTTP session using the psychoclient library. This includes setting custom cookies before requests, retrieving specific cookies from responses, listing all cookies, and deleting cookies. It also shows how to dynamically change redirect behavior. ```go package main import ( "fmt" "net/http" "time" "github.com/sicko7947/psychoclient" ) func main() { session, _ := psychoclient.NewSession(&psychoclient.SessionBuilder{ UseDefaultClient: false, FollowRedirects: false, Timeout: 10 * time.Second, }) defer session.Close() // Manually set cookies before making requests customCookies := map[string]*http.Cookie{ "auth_token": { Name: "auth_token", Value: "Bearer_xyz789", Domain: "example.com", Path: "/", }, "user_id": { Name: "user_id", Value: "12345", }, } session.SetCookies(customCookies) // Make request with pre-set cookies reqID, _ := session.BuildRequest(&psychoclient.RequestBuilder{ Endpoint: "https://example.com/api/data", Method: "GET", Headers: map[string]string{"Accept": "application/json"}, }) resp, _, err := session.Do(reqID) if err != nil { panic(err) } // Response cookies are automatically added to session fmt.Printf("Status: %d\n", resp.StatusCode) // Retrieve specific cookie if token, exists := session.GetCookie("auth_token"); exists { fmt.Printf("Auth token: %s\n", token.Value) } // Get all cookies from session allCookies := session.GetAllCookies() for name, cookie := range allCookies { fmt.Printf("Cookie %s = %s\n", name, cookie.Value) } // Delete specific cookie session.DeleteCookie("user_id") // Change redirect behavior dynamically session.ChangeRedirectBehavier(true) // Now follows redirects // Output: Status: 200 // Auth token: Bearer_xyz789 // Cookie auth_token = Bearer_xyz789 // Cookie session_id = srv_abc123 } ``` -------------------------------- ### Go: Emulate Browser TLS Fingerprint with Psychoclient Source: https://context7.com/sicko7947/psychoclient/llms.txt This Go code demonstrates how to use psychoclient to make HTTP requests with a specific TLS ClientHello fingerprint, emulating a particular browser like Chrome. It highlights setting `UseDefaultClient` to false in `SessionBuilder` to enable custom TLS settings and shows how a request using the default Chrome fingerprint is made. Advanced users can modify or extend the library's TLS specs for other browser fingerprints. ```go package main import ( "fmt" "net/http" "time" "github.com/sicko7947/psychoclient" utls "github.com/refraction-networking/utls" ) func main() { // Using built-in Chrome fingerprint (default) chromeSession, _ := psychoclient.NewSession(&psychoclient.SessionBuilder{ UseDefaultClient: false, // Enables custom TLS FollowRedirects: true, Timeout: 20 * time.Second, }) defer chromeSession.Close() // Request will use Chrome TLS fingerprint reqID, _ := chromeSession.BuildRequest(&psychoclient.RequestBuilder{ Endpoint: "https://tls-fingerprint-test.com/", Method: "GET", Headers: map[string]string{ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0.0.0", }, }) resp, body, err := chromeSession.Do(reqID) if err != nil { panic(err) } fmt.Printf("Chrome fingerprint test: %d\n", resp.StatusCode) fmt.Printf("Response: %s\n", string(body)) // Note: To use custom ClientHello specs beyond Chrome/Firefox, // you need to modify the UHTTPTransport.UTLSClientHelloSpecs field // in the underlying transport, or extend the library with custom specs // The built-in specs support: // - Chrome: GREASE extensions, ALPN h2/http1.1, X25519MLKEM768, compressed certs // - Firefox 135: Different cipher order, X25519MLKEM768, ECH, no GREASE // Output: Chrome fingerprint test: 200 // Response: {"ja3_hash": "771,4865-4866-4867-49195..."} } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.