httpclient

package module
v0.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 27, 2025 License: MIT Imports: 12 Imported by: 0

README

HTTP Client Module

This module provides a configurable HTTP client service that can be used by other modules in the modular framework. It supports configurable connection pooling, timeouts, and optional verbose logging of HTTP requests and responses.

Features

  • Configurable HTTP client settings including connection pooling and timeouts
  • Optional verbose logging of HTTP requests and responses
  • Support for logging to files or application logger
  • Request modifier support for customizing requests before they are sent
  • Easy integration with other modules through service dependencies

Configuration

The module can be configured using YAML, JSON, or environment variables:

httpclient:
  max_idle_conns: 100             # Maximum idle connections across all hosts
  max_idle_conns_per_host: 10     # Maximum idle connections per host
  idle_conn_timeout: 90           # Maximum time an idle connection is kept alive (seconds)
  request_timeout: 30             # Default timeout for HTTP requests (seconds)
  tls_timeout: 10                 # TLS handshake timeout (seconds)
  disable_compression: false      # Whether to disable response body compression
  disable_keep_alives: false      # Whether to disable HTTP keep-alives
  verbose: false                  # Enable verbose logging of HTTP requests and responses
  verbose_options:                # Options for verbose logging (when verbose is true)
    log_headers: true             # Log request and response headers
    log_body: true                # Log request and response bodies
    max_body_log_size: 10000      # Maximum size of logged bodies (bytes)
    log_to_file: false            # Whether to log to files instead of application logger
    log_file_path: "/tmp/logs"    # Directory path for log files (required when log_to_file is true)

Integration with Other Modules

The HTTP client module provides a ClientService that can be used by other modules through service dependency injection. For example, to use this client in the reverseproxy module:

// In reverseproxy module:
func (m *ReverseProxyModule) RequiresServices() []modular.ServiceDependency {
	return []modular.ServiceDependency{
		{
			Name: "router", 
			Required: true, 
			MatchByInterface: true, 
			SatisfiesInterface: reflect.TypeOf((*handleFuncService)(nil)).Elem(),
		},
		{
			Name: "httpclient",
			Required: false, // Optional dependency
			MatchByInterface: true,
			SatisfiesInterface: reflect.TypeOf((*httpclient.ClientService)(nil)).Elem(),
		},
	}
}

Then in the constructor:

func (m *ReverseProxyModule) Constructor() modular.ModuleConstructor {
	return func(app modular.Application, services map[string]any) (modular.Module, error) {
		// Get router service
		handleFuncSvc, ok := services["router"].(handleFuncService)
		if !ok {
			return nil, fmt.Errorf("service %s does not implement HandleFunc interface", "router")
		}
		m.router = handleFuncSvc

		// Get optional HTTP client service
		if clientService, ok := services["httpclient"].(httpclient.ClientService); ok {
			// Use the provided HTTP client
			m.httpClient = clientService.Client()
		} else {
			// Create a default HTTP client
			m.httpClient = &http.Client{
				// Default settings...
			}
		}

		return m, nil
	}
}

Usage Example

package main

import (
	"github.com/GoCodeAlone/modular"
	"github.com/GoCodeAlone/modular/modules/httpclient"
	"github.com/GoCodeAlone/modular/modules/reverseproxy"
)

func main() {
	app := modular.NewApplication()
	
	// Register modules
	app.RegisterModule(httpclient.NewHTTPClientModule())
	app.RegisterModule(reverseproxy.NewModule())
	
	// The reverseproxy module will automatically use the httpclient service if available
	
	// Run the application
	if err := app.Run(); err != nil {
		panic(err)
	}
}

Documentation

Overview

Package httpclient provides a configurable HTTP client module for the modular framework.

Package httpclient provides a configurable HTTP client module for the modular framework.

Package httpclient provides a configurable HTTP client module for the modular framework.

Index

Constants

View Source
const ModuleName = "httpclient"

ModuleName is the name of this module

View Source
const ServiceName = "httpclient"

ServiceName is the name of the service provided by this module

Variables

This section is empty.

Functions

func NewHTTPClientModule

func NewHTTPClientModule() modular.Module

NewHTTPClientModule creates a new instance of the HTTP client module.

Types

type ClientService

type ClientService interface {
	// Client returns the configured http.Client instance
	Client() *http.Client

	// RequestModifier returns a modifier function that can modify a request before it's sent
	RequestModifier() RequestModifierFunc

	// WithTimeout creates a new client with the specified timeout in seconds
	WithTimeout(timeoutSeconds int) *http.Client
}

ClientService defines the interface for the HTTP client service. Any module that needs to make HTTP requests can use this service.

type Config

type Config struct {
	// MaxIdleConns controls the maximum number of idle (keep-alive) connections across all hosts.
	MaxIdleConns int `yaml:"max_idle_conns" json:"max_idle_conns" env:"MAX_IDLE_CONNS"`

	// MaxIdleConnsPerHost controls the maximum idle (keep-alive) connections to keep per-host.
	MaxIdleConnsPerHost int `yaml:"max_idle_conns_per_host" json:"max_idle_conns_per_host" env:"MAX_IDLE_CONNS_PER_HOST"`

	// IdleConnTimeout is the maximum amount of time an idle connection will remain idle before
	// closing itself, in seconds.
	IdleConnTimeout int `yaml:"idle_conn_timeout" json:"idle_conn_timeout" env:"IDLE_CONN_TIMEOUT"`

	// RequestTimeout is the maximum time for a request to complete, in seconds.
	RequestTimeout int `yaml:"request_timeout" json:"request_timeout" env:"REQUEST_TIMEOUT"`

	// TLSTimeout is the maximum time waiting for TLS handshake, in seconds.
	TLSTimeout int `yaml:"tls_timeout" json:"tls_timeout" env:"TLS_TIMEOUT"`

	// DisableCompression disables decompressing response bodies.
	DisableCompression bool `yaml:"disable_compression" json:"disable_compression" env:"DISABLE_COMPRESSION"`

	// DisableKeepAlives disables HTTP keep-alive and will only use connections for a single request.
	DisableKeepAlives bool `yaml:"disable_keep_alives" json:"disable_keep_alives" env:"DISABLE_KEEP_ALIVES"`

	// Verbose enables detailed logging of HTTP requests and responses.
	Verbose bool `yaml:"verbose" json:"verbose" env:"VERBOSE"`

	// VerboseOptions configures the behavior when Verbose is enabled.
	VerboseOptions *VerboseOptions `yaml:"verbose_options" json:"verbose_options" env:"VERBOSE_OPTIONS"`
}

Config defines the configuration for the HTTP client module.

func (*Config) GetTimeout

func (c *Config) GetTimeout(seconds int) time.Duration

GetTimeout converts a timeout value from seconds to time.Duration.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks the configuration values and sets sensible defaults.

type FileLogger

type FileLogger struct {
	// contains filtered or unexported fields
}

FileLogger handles logging HTTP request and response data to files.

func NewFileLogger

func NewFileLogger(baseDir string, logger modular.Logger) (*FileLogger, error)

NewFileLogger creates a new file logger that writes HTTP data to files.

func (*FileLogger) Close

func (f *FileLogger) Close() error

Close closes any open files and cleans up resources.

func (*FileLogger) LogRequest

func (f *FileLogger) LogRequest(id string, data []byte) error

LogRequest writes request data to a file.

func (*FileLogger) LogResponse

func (f *FileLogger) LogResponse(id string, data []byte) error

LogResponse writes response data to a file.

func (*FileLogger) LogTransactionToFile

func (f *FileLogger) LogTransactionToFile(id string, reqData, respData []byte, duration time.Duration, url string) error

LogTransactionToFile logs both request and response data to a single file for easier analysis.

type HTTPClientModule

type HTTPClientModule struct {
	// contains filtered or unexported fields
}

HTTPClientModule implements a configurable HTTP client module.

func (*HTTPClientModule) Client

func (m *HTTPClientModule) Client() *http.Client

Client returns the configured http.Client instance.

func (*HTTPClientModule) Dependencies

func (m *HTTPClientModule) Dependencies() []string

Dependencies returns the names of modules this module depends on.

func (*HTTPClientModule) Init

Init initializes the module with the provided application.

func (*HTTPClientModule) Name

func (m *HTTPClientModule) Name() string

Name returns the name of the module.

func (*HTTPClientModule) ProvidesServices

func (m *HTTPClientModule) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns services provided by this module.

func (*HTTPClientModule) RegisterConfig

func (m *HTTPClientModule) RegisterConfig(app modular.Application) error

RegisterConfig registers the module's configuration.

func (*HTTPClientModule) RequestModifier

func (m *HTTPClientModule) RequestModifier() RequestModifierFunc

RequestModifier returns a modifier function that can modify a request before it's sent.

func (*HTTPClientModule) RequiresServices

func (m *HTTPClientModule) RequiresServices() []modular.ServiceDependency

RequiresServices returns services required by this module.

func (*HTTPClientModule) SetRequestModifier

func (m *HTTPClientModule) SetRequestModifier(modifier RequestModifierFunc)

SetRequestModifier sets the request modifier function.

func (*HTTPClientModule) Start

Start performs startup logic for the module.

func (*HTTPClientModule) Stop

Stop performs shutdown logic for the module.

func (*HTTPClientModule) WithTimeout

func (m *HTTPClientModule) WithTimeout(timeoutSeconds int) *http.Client

WithTimeout creates a new client with the specified timeout in seconds.

type RequestModifierFunc

type RequestModifierFunc func(*http.Request) *http.Request

RequestModifierFunc is a function type that can be used to modify an HTTP request before it is sent by the client.

type VerboseOptions

type VerboseOptions struct {
	// LogHeaders enables logging of request and response headers.
	LogHeaders bool `yaml:"log_headers" json:"log_headers" env:"LOG_HEADERS"`

	// LogBody enables logging of request and response bodies.
	LogBody bool `yaml:"log_body" json:"log_body" env:"LOG_BODY"`

	// MaxBodyLogSize limits the size of logged request and response bodies.
	MaxBodyLogSize int `yaml:"max_body_log_size" json:"max_body_log_size" env:"MAX_BODY_LOG_SIZE"`

	// LogToFile enables logging to files instead of just the logger.
	LogToFile bool `yaml:"log_to_file" json:"log_to_file" env:"LOG_TO_FILE"`

	// LogFilePath is the directory where log files will be written.
	LogFilePath string `yaml:"log_file_path" json:"log_file_path" env:"LOG_FILE_PATH"`
}

VerboseOptions configures the behavior of verbose logging.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL