{"modulePath":"github.com/CrisisTextLine/modular/modules/httpclient","version":"v0.6.0","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package httpclient\n\nPackage httpclient provides a configurable HTTP client module for the modular framework.\n\nPackage httpclient provides a configurable HTTP client module for the modular framework.\n\nPackage httpclient provides a configurable HTTP client module for the modular framework.\n\nThis module offers a production-ready HTTP client with comprehensive configuration options, request/response logging, connection pooling, timeout management, and request modification capabilities. It's designed for reliable HTTP communication in microservices and web applications.\n\n### Features {#hdr-Features}\n\nThe httpclient module provides the following capabilities:\n\n  - Configurable connection pooling and keep-alive settings\n  - Request and response timeout management\n  - TLS handshake timeout configuration\n  - Comprehensive request/response logging with file output\n  - Request modification pipeline for adding headers, authentication, etc.\n  - Performance-optimized transport settings\n  - Support for compression and keep-alive control\n  - Service interface for dependency injection\n\n### Configuration {#hdr-Configuration}\n\nThe module can be configured through the Config structure:\n\n\tconfig := \u0026Config{\n\t    MaxIdleConns:        100,        // total idle connections\n\t    MaxIdleConnsPerHost: 10,         // idle connections per host\n\t    IdleConnTimeout:     90,         // idle connection timeout (seconds)\n\t    RequestTimeout:      30,         // request timeout (seconds)\n\t    TLSTimeout:          10,         // TLS handshake timeout (seconds)\n\t    DisableCompression:  false,      // enable gzip compression\n\t    DisableKeepAlives:   false,      // enable connection reuse\n\t    Verbose:             true,       // enable request/response logging\n\t    VerboseOptions: \u0026VerboseOptions{\n\t        LogToFile:    true,\n\t        LogFilePath:  \"/var/log/httpclient\",\n\t    },\n\t}\n\n### Service Registration {#hdr-Service_Registration}\n\nThe module registers itself as a service for dependency injection:\n\n\t// Get the HTTP client service\n\tclient := app.GetService(\"httpclient\").(httpclient.ClientService)\n\n\t// Use the client\n\tresp, err := client.Client().Get(\"https://api.example.com/users\")\n\n\t// Create a client with custom timeout\n\ttimeoutClient := client.WithTimeout(60)\n\tresp, err := timeoutClient.Post(\"https://api.example.com/upload\", \"application/json\", data)\n\n### Usage Examples {#hdr-Usage_Examples}\n\nBasic HTTP requests:\n\n\t// GET request\n\tresp, err := client.Client().Get(\"https://api.example.com/health\")\n\tif err != nil {\n\t    return err\n\t}\n\tdefer resp.Body.Close()\n\n\t// POST request with JSON\n\tjsonData := bytes.NewBuffer([]byte(`{\"name\": \"test\"}`))\n\tresp, err := client.Client().Post(\n\t    \"https://api.example.com/users\",\n\t    \"application/json\",\n\t    jsonData,\n\t)\n\nRequest modification for authentication:\n\n\t// Set up request modifier for API key authentication\n\tmodifier := func(req *http.Request) *http.Request {\n\t    req.Header.Set(\"Authorization\", \"Bearer \"+apiToken)\n\t    req.Header.Set(\"User-Agent\", \"MyApp/1.0\")\n\t    return req\n\t}\n\tclient.SetRequestModifier(modifier)\n\n\t// All subsequent requests will include the headers\n\tresp, err := client.Client().Get(\"https://api.example.com/protected\")\n\nCustom timeout scenarios:\n\n\t// Short timeout for health checks\n\thealthClient := client.WithTimeout(5)\n\tresp, err := healthClient.Get(\"https://service.example.com/health\")\n\n\t// Long timeout for file uploads\n\tuploadClient := client.WithTimeout(300)\n\tresp, err := uploadClient.Post(\"https://api.example.com/upload\", contentType, fileData)\n\n### Logging and Debugging {#hdr-Logging_and_Debugging}\n\nWhen verbose logging is enabled, the module logs detailed request and response information including headers, bodies, and timing data. This is invaluable for debugging API integrations and monitoring HTTP performance.\n\nLog output includes:\n\n  - Request method, URL, and headers\n  - Request body (configurable)\n  - Response status, headers, and body\n  - Request duration and timing breakdown\n  - Error details and retry information\n\n### Performance Considerations {#hdr-Performance_Considerations}\n\nThe module is optimized for production use with:\n\n  - Connection pooling to reduce connection overhead\n  - Keep-alive connections for better performance\n  - Configurable timeouts to prevent resource leaks\n  - Optional compression to reduce bandwidth usage\n  - Efficient request modification pipeline\n\n## Constants\n\n```go\nconst (\n\t// Client lifecycle events\n\tEventTypeClientCreated    = \"com.modular.httpclient.client.created\"\n\tEventTypeClientStarted    = \"com.modular.httpclient.client.started\"\n\tEventTypeClientConfigured = \"com.modular.httpclient.client.configured\"\n\n\t// Request modifier events\n\tEventTypeModifierSet     = \"com.modular.httpclient.modifier.set\"\n\tEventTypeModifierApplied = \"com.modular.httpclient.modifier.applied\"\n\tEventTypeModifierAdded   = \"com.modular.httpclient.modifier.added\"\n\tEventTypeModifierRemoved = \"com.modular.httpclient.modifier.removed\"\n\n\t// Module lifecycle events\n\tEventTypeModuleStarted = \"com.modular.httpclient.module.started\"\n\tEventTypeModuleStopped = \"com.modular.httpclient.module.stopped\"\n\n\t// Configuration events\n\tEventTypeConfigLoaded   = \"com.modular.httpclient.config.loaded\"\n\tEventTypeTimeoutChanged = \"com.modular.httpclient.timeout.changed\"\n)\n```\nEvent type constants for httpclient module events. Following CloudEvents specification reverse domain notation.\n\n```go\nconst ModuleName = \"httpclient\"\n```\nModuleName is the unique identifier for the httpclient module.\n\n```go\nconst ServiceName = \"httpclient\"\n```\nServiceName is the name of the service provided by this module. Other modules can use this name to request the HTTP client service through dependency injection.\n\n## Variables\n\n```go\nvar (\n\t// ErrNoSubjectForEventEmission is returned when trying to emit events without a subject\n\tErrNoSubjectForEventEmission = errors.New(\"no subject available for event emission\")\n\t// ErrUnsafeFilename is returned when a URL cannot be safely converted to a filename\n\tErrUnsafeFilename = errors.New(\"URL contains no valid characters for filename after sanitization\")\n)\n```\nError definitions\n\n```go\nvar (\n\t// ErrLogFilePathRequired is returned when log_to_file is enabled but log_file_path is not specified\n\tErrLogFilePathRequired = errors.New(\"log_file_path must be specified when log_to_file is enabled\")\n)\n```\n\n## Functions\n\n```go\nfunc NewHTTPClientModule() modular.Module\n```\nNewHTTPClientModule creates a new instance of the HTTP client module. This is the primary constructor for the httpclient module and should be used when registering the module with the application.\n\nExample:\n\n\tapp.RegisterModule(httpclient.NewHTTPClientModule())\n\n## Types\n\n```go\ntype ClientService interface {\n\t// Client returns the configured http.Client instance.\n\t// This client uses the module's configuration for timeouts, connection\n\t// pooling, compression, and other transport settings. The client is\n\t// thread-safe and can be used concurrently.\n\t//\n\t// The returned client includes any configured request modification\n\t// pipeline and verbose logging if enabled.\n\tClient() *http.Client\n\n\t// RequestModifier returns a modifier function that can modify a request before it's sent.\n\t// This function applies any configured request modifications such as\n\t// authentication headers, user agents, or custom headers.\n\t//\n\t// The modifier can be used manually when creating custom requests:\n\t//\treq, _ := http.NewRequest(\"POST\", url, body)\n\t//\treq = modifier(req)\n\t//\tresp, err := client.Do(req)\n\tRequestModifier() RequestModifierFunc\n\n\t// WithTimeout creates a new client with the specified timeout in seconds.\n\t// This is useful for creating clients with different timeout requirements\n\t// without affecting the default client configuration.\n\t//\n\t// The new client inherits all other configuration from the module\n\t// (connection pooling, compression, etc.) but uses the specified timeout.\n\t//\n\t// Common timeout scenarios:\n\t//   - Health checks: 5-10 seconds\n\t//   - API calls: 30-60 seconds\n\t//   - File uploads: 300+ seconds\n\tWithTimeout(timeoutSeconds int) *http.Client\n}\n```\nClientService defines the interface for the HTTP client service. This interface provides access to configured HTTP clients and request modification capabilities. Any module that needs to make HTTP requests can use this service through dependency injection.\n\nThe service provides multiple ways to access HTTP clients:\n\n  - Default client with module configuration\n  - Timeout-specific clients for different use cases\n  - Request modification pipeline for common headers/auth\n\nExample usage:\n\n\t// Basic usage\n\tclient := httpClientService.Client()\n\tresp, err := client.Get(\"https://api.example.com/data\")\n\n\t// Custom timeout\n\tshortTimeoutClient := httpClientService.WithTimeout(5)\n\tresp, err := shortTimeoutClient.Get(\"https://api.example.com/health\")\n\n\t// Request modification\n\tmodifier := httpClientService.RequestModifier()\n\treq, _ := http.NewRequest(\"GET\", \"https://api.example.com/data\", nil)\n\tmodifiedReq := modifier(req)\n\n```go\ntype Config struct {\n\t// MaxIdleConns controls the maximum number of idle (keep-alive) connections across all hosts.\n\t// This setting affects the total connection pool size and memory usage.\n\t// Higher values allow more concurrent connections but use more memory.\n\t// Default: 100\n\tMaxIdleConns int `yaml:\"max_idle_conns\" json:\"max_idle_conns\" env:\"MAX_IDLE_CONNS\"`\n\n\t// MaxIdleConnsPerHost controls the maximum idle (keep-alive) connections to keep per-host.\n\t// This prevents a single host from monopolizing the connection pool.\n\t// Should be tuned based on expected traffic patterns to specific hosts.\n\t// Default: 10\n\tMaxIdleConnsPerHost int `yaml:\"max_idle_conns_per_host\" json:\"max_idle_conns_per_host\" env:\"MAX_IDLE_CONNS_PER_HOST\"`\n\n\t// IdleConnTimeout is the maximum amount of time an idle connection will remain idle\n\t// before closing itself. This helps prevent stale connections and\n\t// reduces server-side resource usage.\n\t// Default: 90 seconds\n\tIdleConnTimeout time.Duration `yaml:\"idle_conn_timeout\" json:\"idle_conn_timeout\" env:\"IDLE_CONN_TIMEOUT\"`\n\n\t// RequestTimeout is the maximum time for a request to complete.\n\t// This includes connection time, any redirects, and reading the response body.\n\t// Use WithTimeout() method for per-request timeout overrides.\n\t// Default: 30 seconds\n\tRequestTimeout time.Duration `yaml:\"request_timeout\" json:\"request_timeout\" env:\"REQUEST_TIMEOUT\"`\n\n\t// TLSTimeout is the maximum time waiting for TLS handshake.\n\t// This only affects HTTPS connections and should be set based on expected\n\t// network latency and certificate chain complexity.\n\t// Default: 10 seconds\n\tTLSTimeout time.Duration `yaml:\"tls_timeout\" json:\"tls_timeout\" env:\"TLS_TIMEOUT\"`\n\n\t// DisableCompression disables decompressing response bodies.\n\t// When false (default), the client automatically handles gzip compression.\n\t// Set to true if you need to handle compression manually or want raw responses.\n\t// Default: false (compression enabled)\n\tDisableCompression bool `yaml:\"disable_compression\" json:\"disable_compression\" env:\"DISABLE_COMPRESSION\"`\n\n\t// DisableKeepAlives disables HTTP keep-alive and will only use connections for a single request.\n\t// This can be useful for debugging or when connecting to servers that don't handle\n\t// keep-alives properly, but significantly impacts performance.\n\t// Default: false (keep-alives enabled)\n\tDisableKeepAlives bool `yaml:\"disable_keep_alives\" json:\"disable_keep_alives\" env:\"DISABLE_KEEP_ALIVES\"`\n\n\t// Verbose enables detailed logging of HTTP requests and responses.\n\t// When enabled, logs include request/response headers, bodies, timing information,\n\t// and error details. Very useful for debugging but can impact performance.\n\t// Default: false\n\tVerbose bool `yaml:\"verbose\" json:\"verbose\" env:\"VERBOSE\"`\n\n\t// VerboseOptions configures the behavior when Verbose is enabled.\n\t// This allows fine-grained control over what gets logged and where.\n\tVerboseOptions *VerboseOptions `yaml:\"verbose_options\" json:\"verbose_options\" env:\"VERBOSE_OPTIONS\"`\n}\n```\nConfig defines the configuration for the HTTP client module. This structure contains all the settings needed to configure HTTP client behavior, connection pooling, timeouts, and logging.\n\nConfiguration can be provided through JSON, YAML, or environment variables. The struct tags define the mapping for each configuration source.\n\nExample YAML configuration:\n\n\tmax_idle_conns: 200\n\tmax_idle_conns_per_host: 20\n\tidle_conn_timeout: 120\n\trequest_timeout: 60\n\ttls_timeout: 15\n\tdisable_compression: false\n\tdisable_keep_alives: false\n\tverbose: true\n\tverbose_options:\n\t  log_headers: true\n\t  log_body: true\n\t  max_body_log_size: 1024\n\t  log_to_file: true\n\t  log_file_path: \"/var/log/httpclient\"\n\nExample environment variables:\n\n\tHTTPCLIENT_MAX_IDLE_CONNS=200\n\tHTTPCLIENT_REQUEST_TIMEOUT=60\n\tHTTPCLIENT_VERBOSE=true\n\n```go\nfunc (c *Config) Validate() error\n```\nValidate checks the configuration values and sets sensible defaults.\n\n```go\ntype FileLogger struct {\n\t// contains filtered or unexported fields\n}\n```\nFileLogger handles logging HTTP request and response data to files.\n\n```go\nfunc NewFileLogger(baseDir string, logger modular.Logger) (*FileLogger, error)\n```\nNewFileLogger creates a new file logger that writes HTTP data to files.\n\n```go\nfunc (f *FileLogger) Close() error\n```\nClose closes any open files and cleans up resources.\n\n```go\nfunc (f *FileLogger) LogRequest(id string, data []byte) error\n```\nLogRequest writes request data to a file.\n\n```go\nfunc (f *FileLogger) LogResponse(id string, data []byte) error\n```\nLogResponse writes response data to a file.\n\n```go\nfunc (f *FileLogger) LogTransactionToFile(id string, reqData, respData []byte, duration time.Duration, url string) error\n```\nLogTransactionToFile logs both request and response data to a single file for easier analysis.\n\n```go\ntype HTTPClientModule struct {\n\t// contains filtered or unexported fields\n}\n```\nHTTPClientModule implements a configurable HTTP client module. It provides a production-ready HTTP client with comprehensive configuration options, logging capabilities, and request modification features.\n\nThe module implements the following interfaces:\n\n  - modular.Module: Basic module lifecycle\n  - modular.Configurable: Configuration management\n  - modular.ServiceAware: Service dependency management\n  - modular.ObservableModule: Event observation and emission\n  - ClientService: HTTP client service interface\n\nThe HTTP client is thread-safe and can be used concurrently from multiple goroutines.\n\n```go\nfunc (m *HTTPClientModule) AddRequestModifier(name string, modifier func(*http.Request) error)\n```\nAddRequestModifier adds a named request modifier function. Named modifiers can be added and removed individually, providing fine-grained control over request modification. Multiple modifiers can be active simultaneously.\n\nThe modifier function should return an error if the request modification fails. If any modifier returns an error, the request will not be sent.\n\n```go\nfunc (m *HTTPClientModule) Client() *http.Client\n```\nClient returns the configured http.Client instance.\n\n```go\nfunc (m *HTTPClientModule) Dependencies() []string\n```\nDependencies returns the names of modules this module depends on.\n\n```go\nfunc (m *HTTPClientModule) EmitEvent(ctx context.Context, event cloudevents.Event) error\n```\nEmitEvent implements the ObservableModule interface. This allows the httpclient module to emit events to registered observers.\n\n```go\nfunc (m *HTTPClientModule) GetRegisteredEventTypes() []string\n```\nGetRegisteredEventTypes implements the ObservableModule interface. Returns all event types that this httpclient module can emit.\n\n```go\nfunc (m *HTTPClientModule) Init(app modular.Application) error\n```\nInit initializes the httpclient module with the application context. This method is called after all modules have been registered and their configurations loaded. It sets up the HTTP client, transport, and logging.\n\nThe initialization process:\n\n 1. Retrieves the module's configuration\n 2. Sets up logging\n 3. Creates and configures the HTTP transport with connection pooling\n 4. Sets up request/response logging if verbose mode is enabled\n 5. Creates the HTTP client with configured transport and middleware\n 6. Initializes request modification pipeline\n\nTransport configuration includes:\n\n  - Connection pooling settings for optimal performance\n  - Timeout configurations for reliability\n  - Compression and keep-alive settings\n  - TLS handshake timeout for secure connections\n\n```go\nfunc (m *HTTPClientModule) Name() string\n```\nName returns the unique identifier for this module. This name is used for service registration, dependency resolution, and configuration section identification.\n\n```go\nfunc (m *HTTPClientModule) ProvidesServices() []modular.ServiceProvider\n```\nProvidesServices returns services provided by this module.\n\n```go\nfunc (m *HTTPClientModule) RegisterConfig(app modular.Application) error\n```\nRegisterConfig registers the module's configuration structure. This method is called during application initialization to register the default configuration values for the httpclient module.\n\nDefault configuration:\n\n  - MaxIdleConns: 100 (total idle connections)\n  - MaxIdleConnsPerHost: 10 (idle connections per host)\n  - IdleConnTimeout: 90 seconds\n  - RequestTimeout: 30 seconds\n  - TLSTimeout: 10 seconds\n  - DisableCompression: false (compression enabled)\n  - DisableKeepAlives: false (keep-alives enabled)\n  - Verbose: false (logging disabled)\n\n```go\nfunc (m *HTTPClientModule) RegisterObservers(subject modular.Subject) error\n```\nRegisterObservers implements the ObservableModule interface. This allows the httpclient module to register as an observer for events it's interested in.\n\n```go\nfunc (m *HTTPClientModule) RemoveRequestModifier(name string)\n```\nRemoveRequestModifier removes a named request modifier function. If the named modifier does not exist, this operation is a no-op.\n\n```go\nfunc (m *HTTPClientModule) RequestModifier() RequestModifierFunc\n```\nRequestModifier returns a modifier function that can modify a request before it's sent.\n\n```go\nfunc (m *HTTPClientModule) RequiresServices() []modular.ServiceDependency\n```\nRequiresServices returns services required by this module.\n\n```go\nfunc (m *HTTPClientModule) SetRequestModifier(modifier RequestModifierFunc)\n```\nSetRequestModifier sets the request modifier function.\n\n```go\nfunc (m *HTTPClientModule) Start(ctx context.Context) error\n```\nStart performs startup logic for the module.\n\n```go\nfunc (m *HTTPClientModule) Stop(ctx context.Context) error\n```\nStop performs shutdown logic for the module.\n\n```go\nfunc (m *HTTPClientModule) WithTimeout(timeoutSeconds int) *http.Client\n```\nWithTimeout creates a new client with the specified timeout in seconds.\n\n```go\ntype HTTPDoer interface {\n\tDo(req *http.Request) (*http.Response, error)\n}\n```\nHTTPDoer defines the minimal interface for making HTTP requests. This interface is implemented by http.Client and provides a simple abstraction for modules that only need to make HTTP requests without the additional features provided by ClientService.\n\nUse this interface when you only need to make HTTP requests:\n\n\ttype MyModule struct {\n\t    httpClient HTTPDoer\n\t}\n\n\tfunc (m *MyModule) RequiresServices() []modular.ServiceDependency {\n\t    return []modular.ServiceDependency{\n\t        {\n\t            Name:               \"http-doer\",\n\t            Required:           true,\n\t            MatchByInterface:   true,\n\t            SatisfiesInterface: reflect.TypeOf((*HTTPDoer)(nil)).Elem(),\n\t        },\n\t    }\n\t}\n\n```go\ntype RequestModifierFunc func(*http.Request) *http.Request\n```\nRequestModifierFunc is a function type that can be used to modify an HTTP request before it is sent by the client.\n\nRequest modifiers are useful for:\n\n  - Adding authentication headers (Bearer tokens, API keys)\n  - Setting common headers (User-Agent, Content-Type)\n  - Adding request tracking (correlation IDs, request IDs)\n  - Request logging and debugging\n  - Request validation and sanitization\n\nExample modifier implementations:\n\n\t// API key authentication\n\tfunc apiKeyModifier(apiKey string) RequestModifierFunc {\n\t    return func(req *http.Request) *http.Request {\n\t        req.Header.Set(\"Authorization\", \"Bearer \"+apiKey)\n\t        return req\n\t    }\n\t}\n\n\t// Request tracing\n\tfunc tracingModifier(req *http.Request) *http.Request {\n\t    req.Header.Set(\"X-Request-ID\", generateRequestID())\n\t    req.Header.Set(\"X-Trace-ID\", getTraceID(req.Context()))\n\t    return req\n\t}\n\n\t// User agent setting\n\tfunc userAgentModifier(userAgent string) RequestModifierFunc {\n\t    return func(req *http.Request) *http.Request {\n\t        req.Header.Set(\"User-Agent\", userAgent)\n\t        return req\n\t    }\n\t}\n\n```go\ntype VerboseOptions struct {\n\t// LogHeaders enables logging of request and response headers.\n\t// This includes all HTTP headers sent and received, which can contain\n\t// sensitive information like authorization tokens.\n\t// Default: false\n\tLogHeaders bool `yaml:\"log_headers\" json:\"log_headers\" env:\"LOG_HEADERS\"`\n\n\t// LogBody enables logging of request and response bodies.\n\t// This can generate large amounts of log data and may contain sensitive\n\t// information. Consider using MaxBodyLogSize to limit logged content.\n\t// Default: false\n\tLogBody bool `yaml:\"log_body\" json:\"log_body\" env:\"LOG_BODY\"`\n\n\t// MaxBodyLogSize limits the size of logged request and response bodies.\n\t// Bodies larger than this size will be truncated in logs.\n\t// Helps prevent log spam from large file uploads or downloads.\n\t// When LogBody is enabled and this is left at 0, Validate() applies a\n\t// safe default of 1024 (1KB) to prevent unbounded log output.\n\t// Default: 1024 (1KB) when LogBody is enabled\n\tMaxBodyLogSize int `yaml:\"max_body_log_size\" json:\"max_body_log_size\" env:\"MAX_BODY_LOG_SIZE\"`\n\n\t// LogToFile enables logging to files instead of just the application logger.\n\t// When enabled, HTTP logs are written to separate files for easier analysis.\n\t// Requires LogFilePath to be set.\n\t// Default: false\n\tLogToFile bool `yaml:\"log_to_file\" json:\"log_to_file\" env:\"LOG_TO_FILE\"`\n\n\t// LogFilePath is the directory where log files will be written.\n\t// Log files are organized by date and include request/response details.\n\t// The directory must be writable by the application.\n\t// Default: \"\" (current directory)\n\tLogFilePath string `yaml:\"log_file_path\" json:\"log_file_path\" env:\"LOG_FILE_PATH\"`\n}\n```\nVerboseOptions configures the behavior of verbose logging. These options provide fine-grained control over HTTP request/response logging to balance debugging needs with performance and security considerations.\n\n","path":"github.com/CrisisTextLine/modular/modules/httpclient","name":"httpclient","synopsis":"Package httpclient provides a configurable HTTP client module for the modular framework.","isRedistributable":true}
