### Go Quick Usage Example for TLS-Client Source: https://github.com/bogdanfinn/tls-client/blob/master/Readme.md Demonstrates how to create an HTTP client with custom options, including timeout, TLS profile, redirect behavior, and cookie jar, then perform a GET request. ```go package main import ( "fmt" "io" "log" http "github.com/bogdanfinn/fhttp" tls_client "github.com/bogdanfinn/tls-client" "github.com/bogdanfinn/tls-client/profiles" ) func main() { jar := tls_client.NewCookieJar() options := []tls_client.HttpClientOption{ tls_client.WithTimeoutSeconds(30), tls_client.WithClientProfile(profiles.Chrome_144), tls_client.WithNotFollowRedirects(), tls_client.WithCookieJar(jar), // create cookieJar instance and pass it as argument } client, err := tls_client.NewHttpClient(tls_client.NewNoopLogger(), options...) if err != nil { log.Println(err) return } req, err := http.NewRequest(http.MethodGet, "https://tls.peet.ws/api/all", nil) if err != nil { log.Println(err) return } req.Header = http.Header{ "accept": {"*/*"}, "accept-language": {"de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7"}, "user-agent": {"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"}, http.HeaderOrderKey: { "accept", "accept-language", "user-agent", }, } resp, err := client.Do(req) if err != nil { log.Println(err) return } defer resp.Body.Close() log.Println(fmt.Sprintf("status code: %d", resp.StatusCode)) readBytes, err := io.ReadAll(resp.Body) if err != nil { log.Println(err) return } log.Println(string(readBytes)) } ``` -------------------------------- ### Complete Bandwidth Monitoring Example Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/06-bandwidth-tracker.md This example shows how to enable bandwidth tracking for an `HttpClient`, make requests, and then retrieve and log the upload, download, and total bandwidth statistics. ```go package main import ( "log" tls_client "github.com/bogdanfinn/tls-client" "github.com/bogdanfinn/tls-client/profiles" ) func main() { // Enable bandwidth tracking client, _ := tls_client.NewHttpClient( tls_client.NewLogger(), tls_client.WithClientProfile(profiles.Chrome_144), tls_client.WithBandwidthTracker(), // Enable tracking ) // Make requests resp1, _ := client.Get("https://api.example.com/large-file.json") resp1.Body.Close() resp2, _ := client.Get("https://api.example.com/another-file.json") resp2.Body.Close() // Check statistics tracker := client.GetBandwidthTracker() log.Printf("Upload: %d bytes", tracker.GetWriteBytes()) log.Printf("Download: %d bytes", tracker.GetReadBytes()) log.Printf("Total: %d bytes", tracker.GetTotalBandwidth()) } ``` -------------------------------- ### Logger and HttpClient Initialization Example Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/09-types.md Demonstrates how to initialize a logger with debug enabled and then create an HttpClient instance using that logger. ```go logger := tls_client.NewDebugLogger(tls_client.NewLogger()) client, _ := tls_client.NewHttpClient(logger) ``` -------------------------------- ### Dynamic Profile Selection Example Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/08-client-profiles.md This example demonstrates how to dynamically select a random client profile for new HTTP client instances. ```go package main import ( "math/rand" tls_client "github.com/bogdanfinn/tls-client" "github.com/bogdanfinn/tls-client/profiles" ) func getRandomProfile() profiles.ClientProfile { allProfiles := []profiles.ClientProfile{ profiles.Chrome_144, profiles.Chrome_150, profiles.Firefox_135, profiles.Safari_IOS_18_0, } return allProfiles[rand.Intn(len(allProfiles))] } func makeRequest(url string) { client, _ := tls_client.NewHttpClient( tls_client.NewNoopLogger(), tls_client.WithClientProfile(getRandomProfile()), ) resp, _ := client.Get(url) defer resp.Body.Close() } ``` -------------------------------- ### BandwidthTracker Interface Example Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/09-types.md Shows how to initialize an HTTP client with bandwidth tracking enabled and access the tracker to view downloaded bytes. ```go client, _ := tls_client.NewHttpClient(logger, tls_client.WithBandwidthTracker(), ) tracker := client.GetBandwidthTracker() log.Println("Downloaded:", tracker.GetReadBytes()) ``` -------------------------------- ### CertificatePinner Interface Example Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/09-types.md Illustrates creating a new certificate pinner with a set of domain-to-pin mappings and then using it to pin a connection. ```go pins := map[string][]string{ "example.com": {"sha256/pin1"}, } pinner, _ := tls_client.NewCertificatePinner(pins) err := pinner.Pin(conn, "example.com") ``` -------------------------------- ### CookieJar Interface Example Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/09-types.md Demonstrates how to create a new HTTP client with a custom cookie jar and retrieve all stored cookies. ```go jar := tls_client.NewCookieJar() client, _ := tls_client.NewHttpClient(logger, tls_client.WithCookieJar(jar), ) allCookies := jar.GetAllCookies() ``` -------------------------------- ### Basic HTTP Request Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/README.md Demonstrates how to create a new HTTP client with a specific TLS profile and make a GET request. ```go import ( tls_client "github.com/bogdanfinn/tls-client" "github.com/bogdanfinn/tls-client/profiles" ) client, _ := tls_client.NewHttpClient(nil, tls_client.WithClientProfile(profiles.Chrome_144), tls_client.WithTimeoutSeconds(30), ) resp, _ := client.Get("https://example.com") def resp.Body.Close() ``` -------------------------------- ### Bandwidth Tracker Example Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/06-bandwidth-tracker.md Demonstrates how to use the `BandwidthTracker`. Without `WithBandwidthTracker()`, `GetBandwidthTracker()` returns a no-op tracker. With it enabled, it returns an active tracker. ```go // Without WithBandwidthTracker() client, _ := tls_client.NewHttpClient(logger) tracker := client.GetBandwidthTracker() // Returns NewNopeTracker() - no recording happens // With WithBandwidthTracker() client, _ := tls_client.NewHttpClient(logger, tls_client.WithBandwidthTracker(), ) tracker := client.GetBandwidthTracker() // Returns actual Tracker - recording happens ``` -------------------------------- ### Create HTTP Client with Custom Proxy Dialer Factory Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/09-types.md Example of providing a custom proxy dialer factory to the HTTP client. This allows for specialized proxy setup and management. ```go factory := func(proxyUrl string, timeout time.Duration, localAddr *net.TCPAddr, headers http.Header, logger Logger) (proxy.ContextDialer, error) { // Custom proxy setup return &customDialer{proxyUrl: proxyUrl}, nil } client, _ := tls_client.NewHttpClient(logger, tls_client.WithProxyDialerFactory(factory), ) ``` -------------------------------- ### Complete WebSocket Client Example Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/04-websocket.md This Go program shows how to initialize an HTTP client with specific TLS profiles, set custom headers, establish a WebSocket connection, and send/receive messages. Ensure to use WithForceHttp1() when creating the HTTP client for WebSocket connections. ```go package main import ( "context" "log" "time" http "github.com/bogdanfinn/fhttp" tls_client "github.com/bogdanfinn/tls-client" "github.com/bogdanfinn/tls-client/profiles" "github.com/bogdanfinn/websocket" ) func main() { // Step 1: Create HTTP client with HTTP/1.1 client, err := tls_client.NewHttpClient( tls_client.NewNoopLogger(), tls_client.WithClientProfile(profiles.Chrome_144), tls_client.WithForceHttp1(), // MANDATORY tls_client.WithTimeoutSeconds(30), ) if err != nil { log.Fatal(err) } // Step 2: Prepare custom headers with order headers := http.Header{ "User-Agent": {"Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}, "Origin": {"https://example.com"}, http.HeaderOrderKey: { "host", "upgrade", "connection", "user-agent", "origin", }, } // Step 3: Create WebSocket ws, err := tls_client.NewWebsocket( tls_client.NewNoopLogger(), tls_client.WithTlsClient(client), tls_client.WithUrl("wss://stream.example.com/ws"), tls_client.WithHeaders(headers), tls_client.WithHandshakeTimeoutMilliseconds(10000), ) if err != nil { log.Fatal(err) } // Step 4: Connect ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() conn, err := ws.Connect(ctx) if err != nil { log.Fatal(err) } defer conn.Close() // Step 5: Use connection log.Println("Connected to WebSocket") // Send a message err = conn.WriteMessage(websocket.TextMessage, []byte(`{"action": "subscribe"}`)) if err != nil { log.Fatal(err) } // Read responses for { msgType, data, err := conn.ReadMessage() if err != nil { log.Println("Connection closed:", err) break } if msgType == websocket.TextMessage { log.Printf("Received: %s\n", string(data)) } } } ``` -------------------------------- ### Create and Use HttpClient Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/01-http-client.md Demonstrates how to create a new HttpClient with a specific TLS profile (Chrome 144) and a timeout, then make a GET request. ```go package main import ( "log" tls_client "github.com/bogdanfinn/tls-client" "github.com/bogdanfinn/tls-client/profiles" ) func main() { // Create a basic client with Chrome 144 profile client, err := tls_client.NewHttpClient( tls_client.NewNoopLogger(), tls_client.WithClientProfile(profiles.Chrome_144), tls_client.WithTimeoutSeconds(30), ) if err != nil { log.Fatal(err) } // Make a request resp, err := client.Get("https://example.com") if err != nil { log.Fatal(err) } defer resp.Body.Close() } ``` -------------------------------- ### Retrieve Monitoring Components Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/00-index.md Gets the bandwidth tracker, dialer, and TLS dialer associated with the client for monitoring purposes. ```go // Monitoring tracker := client.GetBandwidthTracker() dialer := client.GetDialer() tlsDialer := client.GetTLSDialer() ``` -------------------------------- ### Info Logging Example Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/05-logger.md Logs informational messages to indicate general operation status. Use for tracking normal execution flow. ```go logger.Info("Client initialized with profile: %s", "Chrome_144") ``` -------------------------------- ### Debug Logging Example Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/05-logger.md Logs debug-level messages. Use for low priority, development information. Requires a DebugLogger instance. ```go logger := tls_client.NewDebugLogger(tls_client.NewLogger()) logger.Debug("Request to %s, status: %d", url, statusCode) ``` -------------------------------- ### Error Logging Example Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/05-logger.md Logs error messages to indicate failure conditions. Use when an operation could not be completed successfully. ```go logger.Error("Request failed: %v", err) ``` -------------------------------- ### Production API Client with Certificate Pinning Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/07-certificate-pinning.md Use this example to create an HTTP client that pins specific certificates for a production API. It includes an alert handler for security incidents like certificate mismatches. ```go package main import ( "context" "log" "net/http" tls_client "github.com/bogdanfinn/tls-client" "github.com/bogdanfinn/tls-client/profiles" ) func main() { // Certificate pins for production APIs pins := map[string][]string{ "api.production.com": { "sha256/D9tXQN2+l3n3d8wJP+cLnGpCiQHNa2W/WEd/2eeUfqQ=", // Current cert "sha256/5kJvNEMw7agoeffVY+ZopdQD6nzQXahjKZ7KwD4AgWc=", // Backup cert }, } // Alert handler for security incidents securityAlert := func(req *http.Request) { log.Printf("SECURITY ALERT: Certificate pin mismatch for %s - possible MITM attack", req.URL.Host) // In production, could trigger: // - Email alerts // - SMS notifications // - Automatic failover // - Connection shutdown } // Create client with pinning client, err := tls_client.NewHttpClient( tls_client.NewLogger(), tls_client.WithClientProfile(profiles.Chrome_144), tls_client.WithTimeoutSeconds(30), tls_client.WithCertificatePinning(pins, securityAlert), ) if err != nil { log.Fatal(err) } // Make API call - will validate pins resp, err := client.Get("https://api.production.com/users") if err != nil { log.Fatal(err) } defer resp.Body.Close() log.Println("Request successful with validated certificate pin") } ``` -------------------------------- ### Rotate Client Profiles for Evasion Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/08-client-profiles.md This example demonstrates rotating through different client profiles to avoid detection patterns. It initializes a session manager with a list of profiles and creates new HTTP clients with a randomly selected profile for each request. ```go package main import ( "log" "math/rand" "time" tls_client "github.com/bogdanfinn/tls-client" "github.com/bogdanfinn/tls-client/profiles" ) type SessionManager struct { profiles []profiles.ClientProfile current int } func NewSessionManager() *SessionManager { return &SessionManager{ profiles: []profiles.ClientProfile{ profiles.Chrome_144, profiles.Chrome_150, profiles.Firefox_135, profiles.Safari_IOS_18_0, }, current: rand.Intn(4), } } func (s *SessionManager) GetClient() tls_client.HttpClient { profile := s.profiles[s.current] s.current = (s.current + 1) % len(s.profiles) client, _ := tls_client.NewHttpClient( tls_client.NewNoopLogger(), tls_client.WithClientProfile(profile), tls_client.WithTimeoutSeconds(30), ) log.Printf("Created client with profile: %v", profile) return client } func main() { manager := NewSessionManager() for i := 0; i < 5; i++ { client := manager.GetClient() resp, _ := client.Get("https://httpbin.org/headers") defer resp.Body.Close() time.Sleep(time.Second) // Rate limiting } } ``` -------------------------------- ### Calculate Download Speed with Bandwidth Tracker Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/06-bandwidth-tracker.md Get the bandwidth tracker from the client, reset it, perform downloads, and then calculate the download speed in bytes per second and Mbps. ```go tracker := client.GetBandwidthTracker() tracker.Reset() startTime := time.Now() // Download 10 MB for i := 0; i < 10; i++ { client.Get("https://example.com/1mb-file") } elapsed := time.Since(startTime).Seconds() bandwidth := float64(tracker.GetReadBytes()) / elapsed log.Printf("Download speed: %.2f bytes/sec (%.2f Mbps)", bandwidth, bandwidth*8/1_000_000, ) ``` -------------------------------- ### Establish TLS Connection with TLSDialerFunc Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/09-types.md Example of using a TLSDialerFunc to establish a TLS connection. Ensure context with timeout is used for managing connection duration. ```go client, _ := tls_client.NewHttpClient(logger) tlsDialer := client.GetTLSDialer() ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) def cancel() conn, err := tlsDialer(ctx, "tcp", "api.example.com:443") if err != nil { log.Fatal(err) } def conn.Close() ``` -------------------------------- ### GetAllCookies Method Example Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/03-cookie-jar.md Returns all cookies stored in the jar, grouped by their host domain. Modifications to the returned map do not affect the jar's internal state. ```go allCookies := jar.GetAllCookies() for domain, cookies := range allCookies { log.Printf("Domain: %s", domain) for _, cookie := range cookies { log.Printf(" %s=%s", cookie.Name, cookie.Value) } } ``` -------------------------------- ### Warn Logging Example Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/05-logger.md Logs warning messages for potentially problematic situations that do not stop execution. Use to alert about non-critical issues. ```go logger.Warn("Cookie jar not configured, cookies will not persist") ``` -------------------------------- ### Cookies Method Example Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/03-cookie-jar.md Retrieves all applicable cookies for a URL. Automatically filters out expired or empty cookies unless configured otherwise. ```go url, _ := url.Parse("https://api.example.com") cookies := jar.Cookies(url) for _, cookie := range cookies { log.Printf("%s=%s", cookie.Name, cookie.Value) } ``` -------------------------------- ### Implement Certificate Pinning with Custom Handler Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/09-types.md Example of setting up certificate pinning with a custom handler that logs security alerts. This handler is invoked when a certificate pin mismatch is detected. ```go handler := func(req *http.Request) { log.Printf("SECURITY: Bad certificate pin for %s", req.URL.Host) // Could trigger alerts, shutdown, etc. } pins := map[string][]string{ "api.example.com": {"sha256/pin1", "sha256/pin2"}, } client, _ := tls_client.NewHttpClient(logger, tls_client.WithCertificatePinning(pins, handler), ) ``` -------------------------------- ### Manage Client Cookies Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/00-index.md Allows setting and retrieving a cookie jar, as well as getting and setting specific cookies for a given URL. ```go // Cookies client.SetCookieJar(jar) jar := client.GetCookieJar() cookies := client.GetCookies(url) client.SetCookies(url, cookies) ``` -------------------------------- ### Execute HTTP Request Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/00-index.md Performs an HTTP request using the client. Supports various methods like Do, Get, Head, and Post. ```go // Execution resp, err := client.Do(req) resp, err := client.Get(url) resp, err := client.Head(url) resp, err := client.Post(url, contentType, body) ``` -------------------------------- ### Concurrent Usage of Bandwidth Tracker Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/06-bandwidth-tracker.md Demonstrates safe concurrent usage of the bandwidth tracker by making multiple GET requests from different goroutines and reading the total bandwidth. ```go // Safe concurrent usage for i := 0; i < 10; i++ { go func() { resp, _ := client.Get("https://example.com") resp.Body.Close() // Safe concurrent read total := tracker.GetTotalBandwidth() }() } ``` -------------------------------- ### SetCookies Method Example Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/03-cookie-jar.md Sets cookies for a given URL. Handles deduplication and optional existing cookie management based on configuration. ```go url, _ := url.Parse("https://example.com") cookies := []*http.Cookie{ { Name: "session_id", Value: "abc123", }, { Name: "user_id", Value: "456", }, } jar.SetCookies(url, cookies) // Subsequent calls add or update moreCookies := []*http.Cookie{ { Name: "session_id", // Will overwrite previous value Value: "xyz789", }, } jar.SetCookies(url, moreCookies) ``` -------------------------------- ### Get Bandwidth Tracker Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/01-http-client.md Retrieve the bandwidth tracker to monitor upload and download bytes. Use this to observe network traffic associated with client requests. ```go tracker := client.GetBandwidthTracker() // Make requests... log.Println("Total:", tracker.GetTotalBandwidth(), "bytes") log.Println("Read:", tracker.GetReadBytes(), "bytes") log.Println("Write:", tracker.GetWriteBytes(), "bytes") ``` -------------------------------- ### Example usage of ErrContinueHooks in Go Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/09-types.md Demonstrates how to return ErrContinueHooks from a hook function to signal a warning or non-critical error, allowing other hooks to execute. The error is wrapped to preserve context. ```go hook := func(req *http.Request) error { if invalid { return fmt.Errorf("warning: %w", tls_client.ErrContinueHooks) } return nil } ``` -------------------------------- ### Configure WebSocket with TLS Client Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/04-websocket.md Sets a custom HTTP client for TLS fingerprinting and connection setup. The HTTP client must be configured with `WithForceHttp1()` to ensure compatibility with the WebSocket upgrade mechanism. ```go // CORRECT: HTTP/1.1 enforced client, _ := tls_client.NewHttpClient(nil, tls_client.WithForceHttp1(), tls_client.WithClientProfile(profiles.Chrome_144), ) ws, _ := tls_client.NewWebsocket(nil, tls_client.WithTlsClient(client), tls_client.WithUrl("wss://example.com/ws"), ) ``` ```go // WRONG: Will fail with HTTP/2 or HTTP/3 client2, _ := tls_client.NewHttpClient(nil, // Missing WithForceHttp1()! ) ``` -------------------------------- ### WithTlsClient Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/04-websocket.md Sets the HTTP client to use for TLS fingerprinting and connection setup. The HTTP client MUST be created with `WithForceHttp1()` option as WebSocket requires HTTP/1.1 upgrade mechanism. ```APIDOC ## WithTlsClient Sets the HTTP client to use for TLS fingerprinting and connection setup. ### Method ```go func WithTlsClient(tlsClient HttpClient) WebsocketOption ``` ### Parameters #### Path Parameters - **tlsClient** (HttpClient) - Required - Configured HTTP client instance ### CRITICAL REQUIREMENT The HTTP client MUST be created with `WithForceHttp1()` option. WebSocket requires HTTP/1.1 upgrade mechanism. ### Why WebSocket upgrade happens via HTTP/1.1 Upgrade header. HTTP/2 and HTTP/3 don't support this mechanism. ### Request Example ```go // CORRECT: HTTP/1.1 enforced client, _ := tls_client.NewHttpClient(nil, tls_client.WithForceHttp1(), tls_client.WithClientProfile(profiles.Chrome_144), ) ws, _ := tls_client.NewWebsocket(nil, tls_client.WithTlsClient(client), tls_client.WithUrl("wss://example.com/ws"), ) // WRONG: Will fail with HTTP/2 or HTTP/3 client2, _ := tls_client.NewHttpClient(nil, // Missing WithForceHttp1()! ) ``` ``` -------------------------------- ### Set New Cookie Jar Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/01-http-client.md Replaces the client's current cookie jar with a new instance. Use this to manage cookies, for example, to start with a fresh set of cookies. ```go newJar := tls_client.NewCookieJar() client.SetCookieJar(newJar) // Now the client uses a fresh jar with no cookies ``` -------------------------------- ### Perform HTTP GET Request Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/01-http-client.md Use Get for simple HTTP GET requests. Remember to close the response body to avoid leaks. This method handles basic GET requests and returns the response or an error. ```go resp, err := client.Get("https://example.com/api/resource") if err != nil { log.Fatal(err) } deferr resp.Body.Close() body, _ := io.ReadAll(resp.Body) ``` -------------------------------- ### Get Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/01-http-client.md Performs an HTTP GET request to the specified URL. The caller must close the response body. ```APIDOC ## Get ### Description Performs an HTTP GET request to the specified URL. The caller must close the response body. ### Method GET ### Endpoint [url] ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go resp, err := client.Get("https://example.com/api/resource") if err != nil { log.Fatal(err) } deffer resp.Body.Close() body, _ := io.ReadAll(resp.Body) ``` ### Response #### Success Response (200 OK) - `*http.Response` - HTTP response; caller must close body #### Response Example (Response body depends on the URL) ```go // Example response body structure (depends on the actual API) { "resource_data": "details" } ``` ``` -------------------------------- ### Example PostResponseHookFunc in Go Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/09-types.md An example of a PostResponseHookFunc that logs the HTTP status code and any request errors. This hook is useful for monitoring and debugging. ```go hook := func(ctx *PostResponseContext) error { if ctx.Response != nil { log.Printf("Status: %d for %s", ctx.Response.StatusCode, ctx.Request.URL) } if ctx.Error != nil { log.Printf("Request error: %v", ctx.Error) } return nil } client.AddPostResponseHook(hook) ``` -------------------------------- ### Initialize TLS Client and Make Request Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/00-index.md Shows how to create a new TLS-aware HTTP client and perform a request. Ensure you have the necessary logger and options configured. ```go import "github.com/bogdanfinn/tls-client" client, _ := tls_client.NewHttpClient(logger, options...) resp, _ := client.Do(request) ``` -------------------------------- ### Example PreRequestHookFunc in Go Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/09-types.md An example of a PreRequestHookFunc that sets a custom 'X-Request-ID' header. This hook can be added to the client to modify outgoing requests. ```go hook := func(req *http.Request) error { req.Header.Set("X-Request-ID", generateID()) return nil } client.AddPreRequestHook(hook) ``` -------------------------------- ### Create Basic HTTP Client Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/00-index.md Initializes a new HTTP client with default settings and a specified client profile. Use this for standard HTTP requests. ```go client, _ := tls_client.NewHttpClient( tls_client.NewLogger(), tls_client.WithClientProfile(profiles.Chrome_144), tls_client.WithTimeoutSeconds(30), ) resp, _ := client.Get("https://example.com") deferr resp.Body.Close() ``` -------------------------------- ### GetBandwidthTracker Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/01-http-client.md Retrieves the bandwidth tracker for monitoring upload and download bytes. The tracker provides methods to reset, get total bandwidth, and get read/write bytes. ```APIDOC ## GetBandwidthTracker ### Description Returns the bandwidth tracker for monitoring upload/download bytes. ### Signature ```go func (c *httpClient) GetBandwidthTracker() bandwidth.BandwidthTracker ``` ### Returns - `bandwidth.BandwidthTracker` - Tracker interface with methods: Reset(), GetTotalBandwidth(), GetReadBytes(), GetWriteBytes() ### Example ```go tracker := client.GetBandwidthTracker() // Make requests... log.Println("Total:", tracker.GetTotalBandwidth(), "bytes") log.Println("Read:", tracker.GetReadBytes(), "bytes") log.Println("Write:", tracker.GetWriteBytes(), "bytes") ``` ``` -------------------------------- ### Create and Connect Websocket Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/09-types.md Instantiate a new Websocket client with options and establish a connection. Ensure to close the connection when done. ```go ws, _ := tls_client.NewWebsocket(logger, tls_client.WithTlsClient(client), tls_client.WithUrl("wss://example.com/ws"), ) conn, _ := ws.Connect(context.Background()) defer conn.Close() ``` -------------------------------- ### Initialize HTTP Client Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/00-index.md Use this constructor to create a new HTTP client instance. Requires a logger and optional configuration options. ```go // HTTP Client client, err := tls_client.NewHttpClient(logger, options...) ``` -------------------------------- ### Get Current Proxy URL Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/01-http-client.md Retrieves the currently configured proxy URL. Returns an empty string if no proxy is set. ```go proxyUrl := client.GetProxy() log.Println("Current proxy:", proxyUrl) ``` -------------------------------- ### Initialize Bandwidth Tracker Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/00-index.md Creates a new bandwidth tracker instance for monitoring network traffic. ```go // Bandwidth tracker := bandwidth.NewTracker() ``` -------------------------------- ### Initialize WebSocket Client Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/00-index.md Establishes a new WebSocket connection. Requires a logger and optional configuration options. ```go // WebSocket ws, err := tls_client.NewWebsocket(logger, options...) ``` -------------------------------- ### Create and Connect WebSocket Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/04-websocket.md Demonstrates creating an HTTP client with HTTP/1.1 forced, then initializing and connecting a WebSocket using the tls-client library. Ensure WithTlsClient and WithUrl options are provided for WebSocket creation. ```go package main import ( tls_client "github.com/bogdanfinn/tls-client" "github.com/bogdanfinn/tls-client/profiles" "context" "github.com/gorilla/websocket" ) func main() { // 1. Create HTTP client with HTTP/1.1 forced (REQUIRED for WebSocket) client, _ := tls_client.NewHttpClient(nil, tls_client.WithClientProfile(profiles.Chrome_133), tls_client.WithForceHttp1(), // CRITICAL tls_client.WithTimeoutSeconds(30), ) // 2. Create WebSocket ws, err := tls_client.NewWebsocket(nil, tls_client.WithTlsClient(client), tls_client.WithUrl("wss://echo.websocket.org/"), ) if err != nil { panic(err) } // 3. Connect conn, err := ws.Connect(context.Background()) if err != nil { panic(err) } defer conn.Close() // 4. Use connection conn.WriteMessage(websocket.TextMessage, []byte("Hello")) _, msg, _ := conn.ReadMessage() println(string(msg)) } ``` -------------------------------- ### Initialize CookieJar and HttpClient Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/03-cookie-jar.md Demonstrates how to create a new CookieJar and integrate it with an HttpClient. Subsequent requests made with this client will automatically manage cookies. ```go jar := tls_client.NewCookieJar() client, _ := tls_client.NewHttpClient(logger, tls_client.WithCookieJar(jar), ) // Login - server returns Set-Cookie client.Get("https://example.com/login") // Subsequent requests automatically include cookies client.Get("https://example.com/api/data") // Manual cookie inspection allCookies := jar.GetAllCookies() ``` -------------------------------- ### Get Underlying Dialer Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/01-http-client.md Retrieves the context dialer used by the client for establishing TCP connections. This can be used for custom connection logic. ```go dialer := client.GetDialer() // Use for custom connection scenarios ``` -------------------------------- ### HTTP Client with Request/Response Hooks Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/00-index.md Sets up an HTTP client with pre-request and post-response hooks. Pre-hooks can modify requests, while post-hooks can process responses. ```go client, _ := tls_client.NewHttpClient( tls_client.NewLogger(), tls_client.WithPreHook(func(req *http.Request) error { req.Header.Set("X-Request-ID", generateID()) return nil }), tls_client.WithPostHook(func(ctx *PostResponseContext) error { log.Printf("Response: %d", ctx.Response.StatusCode) return nil }), ) ``` -------------------------------- ### Get Current Cookie Jar Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/01-http-client.md Retrieves the client's active cookie jar. This can be used to inspect or manipulate cookies directly. ```go jar := client.GetCookieJar() allCookies := jar.Cookies(parsedUrl) for _, cookie := range allCookies { log.Println(cookie.Name, "=", cookie.Value) } ``` -------------------------------- ### HTTP Client with Bandwidth Monitoring Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/00-index.md Initializes an HTTP client with bandwidth tracking enabled. Allows monitoring of downloaded data for specific requests. ```go client, _ := tls_client.NewHttpClient( tls_client.NewLogger(), tls_client.WithBandwidthTracker(), ) resp, _ := client.Get("https://example.com/file.zip") resp.Body.Close() tracker := client.GetBandwidthTracker() log.Printf("Downloaded: %d bytes", tracker.GetReadBytes()) ``` -------------------------------- ### Get Total Bandwidth Usage Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/06-bandwidth-tracker.md Calculates and returns the sum of all bytes read and written. Useful for an overall bandwidth consumption figure. ```go tracker := client.GetBandwidthTracker() total := tracker.GetTotalBandwidth() log.Printf("Total: %d bytes", total) ``` -------------------------------- ### Creating a WebSocket Client with HTTP Client Reference Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/04-websocket.md This snippet shows how to initialize a WebSocket client, ensuring it references an existing HTTP client. This is crucial for inheriting TLS fingerprinting and TCP dialing configurations from the parent HTTP client. ```go client := tls_client.NewHttpClient(...) // Parent ws := tls_client.NewWebsocket(..., tls_client.WithTlsClient(client), // References parent ) ``` -------------------------------- ### Get Downloaded Bytes Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/06-bandwidth-tracker.md Retrieves the total number of bytes downloaded since the tracker was created or last reset. This operation is thread-safe. ```go tracker := client.GetBandwidthTracker() downloadedBytes := tracker.GetReadBytes() log.Printf("Downloaded: %d bytes (%.2f MB)", downloadedBytes, float64(downloadedBytes)/1024/1024) ``` -------------------------------- ### Get Uploaded Bytes Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/06-bandwidth-tracker.md Retrieves the total number of bytes uploaded since the tracker was created or last reset. This operation is thread-safe. ```go tracker := client.GetBandwidthTracker() uploadedBytes := tracker.GetWriteBytes() log.Printf("Uploaded: %d bytes (%.2f MB)", uploadedBytes, float64(uploadedBytes)/1024/1024) ``` -------------------------------- ### Enable Protocol Racing (HTTP/2 and HTTP/3) Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/02-http-client-options.md Activate WithProtocolRacing to enable simultaneous initiation of HTTP/3 (QUIC) and HTTP/2 (TCP) connections, similar to Chrome's 'Happy Eyeballs'. The faster connection is used, and the client remembers successful protocols for future requests to the same host. ```go client, _ := tls_client.NewHttpClient(logger, tls_client.WithProtocolRacing(), ) ``` -------------------------------- ### BandwidthTracker Interface Definition Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/06-bandwidth-tracker.md Defines the contract for bandwidth tracking, including methods to reset, get byte counts, and track connections. ```go type BandwidthTracker interface { Reset() GetTotalBandwidth() int64 GetWriteBytes() int64 GetReadBytes() int64 TrackConnection(ctx context.Context, conn net.Conn) net.Conn } ``` -------------------------------- ### Initialize Certificate Pinner Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/00-index.md Sets up certificate pinning with a list of provided pins. Returns an error if initialization fails. ```go // Pinning pinner, err := tls_client.NewCertificatePinner(pins) ``` -------------------------------- ### Migrating TLS Client Profiles Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/08-client-profiles.md Shows how to create a new HTTP client with a different TLS profile. Profiles cannot be changed on an existing client. ```go client, _ := tls_client.NewHttpClient(logger, tls_client.WithClientProfile(profiles.Chrome_144), ) // Later, to change profile, create a new client newClient, _ := tls_client.NewHttpClient(logger, tls_client.WithClientProfile(profiles.Firefox_135), ) ``` -------------------------------- ### Connect to WebSocket Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/04-websocket.md Establishes a WebSocket connection using a context for cancellation and timeouts. Ensure the context is properly managed to avoid resource leaks. ```go ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() conn, err := ws.Connect(ctx) if err != nil { log.Printf("WebSocket connection failed: %v", err) return } defer conn.Close() // Connection is ready to use ``` -------------------------------- ### NewHttpClient Constructor Signature Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/01-http-client.md Shows the signature for creating a new HttpClient instance, accepting a logger and variadic options for configuration. ```go func NewHttpClient(logger Logger, options ...HttpClientOption) (HttpClient, error) ``` -------------------------------- ### HTTP Request with Cookies and Proxy Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/README.md Shows how to configure an HTTP client with a cookie jar and a proxy server for making requests. ```go jar := tls_client.NewCookieJar() client, _ := tls_client.NewHttpClient(tls_client.NewLogger(), tls_client.WithClientProfile(profiles.Chrome_144), tls_client.WithCookieJar(jar), tls_client.WithProxyUrl("http://proxy:8080"), ) resp, _ := client.Get("https://example.com") ``` -------------------------------- ### Get Redirect Following Policy Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/01-http-client.md Use GetFollowRedirect to retrieve the current setting for automatic redirect following. This returns a boolean indicating the policy. ```go isFollowing := client.GetFollowRedirect() log.Println("Following redirects:", isFollowing) ``` -------------------------------- ### Initialize Cookie Jar Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/00-index.md Creates a new cookie jar for managing cookies. Accepts optional configuration options. ```go // Cookie Jar jar := tls_client.NewCookieJar(options...) ``` -------------------------------- ### Create HTTP Client with CloudflareCustom Profile Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/08-client-profiles.md Instantiate an HTTP client using the specific CloudflareCustom profile for compatibility. ```go client, _ := tls_client.NewHttpClient(logger, tls_client.WithClientProfile(profiles.CloudflareCustom), ) ``` -------------------------------- ### Get Cookies for a URL Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/01-http-client.md Retrieves all cookies currently stored for a specific URL in the client's cookie jar. Useful for checking which cookies are active. ```go url, _ := url.Parse("https://example.com") cookies := client.GetCookies(url) for _, cookie := range cookies { log.Printf("%s=%s", cookie.Name, cookie.Value) } ``` -------------------------------- ### Configure HTTP or SOCKS5 Proxy with WithProxyUrl Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/02-http-client-options.md Use WithProxyUrl to set up an HTTP or SOCKS5 proxy. Supports basic authentication. ```go client, _ := tls_client.NewHttpClient(logger, tls_client.WithProxyUrl("http://proxy.example.com:8080"), ) ``` ```go client, _ := tls_client.NewHttpClient(logger, tls_client.WithProxyUrl("socks5://user:password@proxy.example.com:1080"), ) ``` -------------------------------- ### WebSocket Connection Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/README.md Illustrates how to establish a WebSocket connection using the TLS client, forcing HTTP/1.1. ```go client, _ := tls_client.NewHttpClient(nil, tls_client.WithForceHttp1(), tls_client.WithClientProfile(profiles.Chrome_144), ) ws, _ := tls_client.NewWebsocket(nil, tls_client.WithTlsClient(client), tls_client.WithUrl("wss://example.com/ws"), ) conn, _ := ws.Connect(context.Background()) def conn.Close() ``` -------------------------------- ### Enable Bandwidth Tracking for HTTP Client Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/02-http-client-options.md Use WithBandwidthTracker to enable upload and download monitoring for an HTTP client. Access the tracker after requests to get byte counts. ```go client, _ := tls_client.NewHttpClient(logger, tls_client.WithBandwidthTracker(), ) // After requests tracker := client.GetBandwidthTracker() log.Println("Upload:", tracker.GetWriteBytes()) log.Println("Download:", tracker.GetReadBytes()) ``` -------------------------------- ### Create Default HTTP Client Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/02-http-client-options.md ProvideDefaultClient creates an HTTP client with sensible defaults and a new cookie jar. Ensure to handle potential errors during client creation. ```go client, err := tls_client.ProvideDefaultClient(tls_client.NewLogger()) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Configure HTTP Client Options Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/00-index.md Provides various option functions to configure the HTTP client, such as setting profiles, timeouts, proxies, and redirect behavior. ```go // Client configuration WithClientProfile(profile) WithTimeoutSeconds(sec) WithTimeoutMilliseconds(ms) WithProxyUrl(url) WithCookieJar(jar) WithNotFollowRedirects() WithForceHttp1() WithProtocolRacing() WithCertificatePinning(pins, handler) WithBandwidthTracker() WithDebug() WithCatchPanics() // ... and more ``` -------------------------------- ### Create New Bandwidth Tracker Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/06-bandwidth-tracker.md Instantiates a new bandwidth tracker with atomic counters. This tracker can be integrated with the HttpClient. ```go tracker := bandwidth.NewTracker() // Use with HttpClient client, _ := tls_client.NewHttpClient(logger, tls_client.WithBandwidthTracker(), // Enables tracker ) // Access tracker stats := client.GetBandwidthTracker() ``` -------------------------------- ### Handle DNS Resolution Error Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/10-errors.md This example shows how to catch DNS resolution errors, which can manifest as net.DNSError or net.OpError. It's useful when a hostname cannot be resolved to an IP address. ```go resp, err := client.Get("https://nonexistent.invalid.domain.example.com") if err != nil { var dnsErr *net.DNSError if errors.As(err, &dnsErr) { log.Println("DNS error:", dnsErr.Err) } } ``` -------------------------------- ### Create Standard Logger Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/05-logger.md Create a logger that outputs Info, Warn, and Error messages to stdout. Debug messages are ignored by default. ```go client, _ := tls_client.NewHttpClient( tls_client.NewLogger(), // Logs info/warn/error only ) ``` -------------------------------- ### Get TLS Dialer for WebSockets Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/01-http-client.md Obtains a TLS dialer function specifically designed to maintain TLS fingerprinting for WebSocket connections. This ensures consistency with regular HTTP requests. ```go tlsDialer := client.GetTLSDialer() // Used internally by websocket connections ``` -------------------------------- ### Initialize Loggers Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/00-index.md Provides different logger implementations: a standard logger, a no-operation logger, and a debug logger that wraps another logger. ```go // Loggers logger := tls_client.NewLogger() logger := tls_client.NewNoopLogger() logger := tls_client.NewDebugLogger(baseLogger) ``` -------------------------------- ### Configure WebSocket Options Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/09-types.md Configure WebSocket connections using WebsocketOption functions, specifying the URL, HTTP client, headers, buffer sizes, and handshake timeout. The URL and HTTP client are required. ```go type WebsocketOption func(config *websocketConfig) ``` ```go ws, _ := tls_client.NewWebsocket(logger, tls_client.WithTlsClient(client), tls_client.WithUrl("wss://example.com/ws"), tls_client.WithReadBufferSize(8192), ) ``` -------------------------------- ### Use Post-Quantum Cryptography Profile Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/08-client-profiles.md Use post-quantum cryptography profiles for testing compatibility with PQ algorithms. ```go tls_client.WithClientProfile(profiles.Chrome_116_PSK_PQ) ``` -------------------------------- ### Fix Empty URL Error for Websocket Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/10-errors.md Ensure a non-empty URL is provided when creating a websocket connection using WithUrl. The WRONG example demonstrates the error when the URL is missing. ```go // WRONG ws, err := tls_client.NewWebsocket(logger, tls_client.WithTlsClient(client), ) ``` ```go // CORRECT ws, err := tls_client.NewWebsocket(logger, tls_client.WithTlsClient(client), tls_client.WithUrl("wss://example.com/ws"), ) ``` -------------------------------- ### Accessing TLS Client Profiles Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/08-client-profiles.md Demonstrates direct access to predefined profiles and access via a map from the profiles package. ```go import "github.com/bogdanfinn/tls-client/profiles" // Direct access profiles.Chrome_150 profiles.Firefox_135 profiles.Safari_IOS_18_0 // Via map profiles.MappedTLSClients["chrome_150"] ``` -------------------------------- ### Bandwidth-Aware Request Limiter Implementation Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/06-bandwidth-tracker.md This Go struct implements a request limiter that monitors bandwidth usage per request. It checks if the bytes read during a GET request exceed the defined limit. ```go type BandwidthLimiter struct { client tls_client.HttpClient tracker bandwidth.BandwidthTracker limit int64 // bytes per second } func (bl *BandwidthLimiter) LimitedGet(url string) (*http.Response, error) { tracker := bl.client.GetBandwidthTracker() before := tracker.GetReadBytes() resp, err := bl.client.Get(url) after := tracker.GetReadBytes() bytesUsed := after - before allowance := bl.limit - bytesUsed if allowance < 0 { // Rate limit exceeded log.Printf("Bandwidth limit exceeded: used %d, limit %d", bytesUsed, bl.limit) } return resp, err } ``` -------------------------------- ### Handle Context Deadline Exceeded Error Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/10-errors.md This example shows how to detect and handle request timeouts using errors.Is with context.DeadlineExceeded. It's triggered by short timeouts set via WithTimeoutSeconds or WithTimeoutMilliseconds. ```go client, _ := tls_client.NewHttpClient(logger, tls_client.WithTimeoutSeconds(1), // Very short timeout ) resp, err := client.Get("https://slow-server.example.com") if err != nil { if errors.Is(err, context.DeadlineExceeded) { log.Println("Request timeout") } } ``` -------------------------------- ### Initialize CookieJar with Logger Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/05-logger.md Use `WithLogger` to provide a custom logger instance to the CookieJar. `NewLogger()` creates a default logger. ```go jar := tls_client.NewCookieJar( tls_client.WithLogger(tls_client.NewLogger()), ) ``` -------------------------------- ### Bandwidth Tracking Reset Strategies Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/06-bandwidth-tracker.md Demonstrates different strategies for resetting the bandwidth tracker based on measurement periods. Use 'Per-Request' for individual request tracking, 'Per-Batch' for grouped requests within a time window, and 'Cumulative' for lifetime tracking. ```go for _, url := range urls { tracker.Reset() resp, _ := client.Get(url) log.Printf("Request: %d bytes", tracker.GetTotalBandwidth()) } ``` ```go tracker.Reset() // ... make many requests for one hour ... stats := tracker.GetTotalBandwidth() // Record or alert on stats ``` ```go // Track lifetime bandwidth resp, _ := client.Get(url) total := tracker.GetTotalBandwidth() // Always increasing ``` -------------------------------- ### Fix Nil TLS Client Error for Websocket Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/10-errors.md When creating a websocket connection, ensure a valid TLS client is provided using WithTlsClient. The WRONG example shows the error condition where tlsClient is nil. ```go // WRONG ws, err := tls_client.NewWebsocket(logger) ``` ```go // CORRECT client, _ := tls_client.NewHttpClient(logger, tls_client.WithForceHttp1()) ws, err := tls_client.NewWebsocket(logger, tls_client.WithTlsClient(client), tls_client.WithUrl("wss://example.com"), ) ``` -------------------------------- ### Track API Endpoint Bandwidth Usage Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/06-bandwidth-tracker.md Iterate through a list of endpoints, reset the tracker for each, make a GET request, and record the number of bytes read from the response body. Ensure the response body is closed after reading. ```go endpoints := []string{ "https://api.example.com/users", "https://api.example.com/posts", "https://api.example.com/comments", } results := make(map[string]int64) tracker := client.GetBandwidthTracker() for _, endpoint := range endpoints { tracker.Reset() resp, _ := client.Get(endpoint) resp.Body.Close() results[endpoint] = tracker.GetReadBytes() } // results now has bandwidth per endpoint for endpoint, bytes := range results { log.Printf("%s: %d bytes", endpoint, bytes) } ``` -------------------------------- ### Configure HttpClient Options Source: https://github.com/bogdanfinn/tls-client/blob/master/_autodocs/09-types.md Define a slice of HttpClientOption functions to configure the behavior of a new HTTP client. These options are passed variadically to the NewHttpClient function. ```go options := []tls_client.HttpClientOption{ tls_client.WithTimeoutSeconds(30), tls_client.WithClientProfile(profiles.Chrome_144), tls_client.WithProxyUrl("http://proxy:8080"), } client, _ := tls_client.NewHttpClient(logger, options...) ```