httputil

package
v1.4.2 Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2023 License: UPL-1.0 Imports: 15 Imported by: 0

Documentation

Overview

Package httputil provides utility functions used for HTTP clients.

Index

Constants

This section is empty.

Variables

View Source
var DefaultHTTPClient = &HTTPClient{
	client: http.DefaultClient,
}

DefaultHTTPClient is a default HTTPClient instance that is ready to use.

Functions

func BasicAuth

func BasicAuth(clientID string, clientSecret []byte) string

BasicAuth returns a basic authentication string of the format:

Basic base64(clientId:clientSecret)

func NewGetRequest

func NewGetRequest(url string) (*http.Request, error)

NewGetRequest create an http GET request using the specified url.

func NewPostRequest

func NewPostRequest(url string, data []byte) (*http.Request, error)

NewPostRequest creates an http POST request using the specified url and data. It wraps data into an io.Reader and calls http.NewRequest with POST method.

func UTF8Encode

func UTF8Encode(s string) []byte

UTF8Encode returns the UTF-8 encoding of the specified string.

Types

type HTTPClient

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

HTTPClient represents an HTTP client. It is used to handle connections, send HTTP requests to and receive HTTP responses from server. It is implemented based on http.client, providing convenient configuration options to take control of client connections.

The underlying http.client's Transport maintains internal state, such as cached TCP connections, which can be reused. So an HTTPClient can handle multiple client connections, it should be reused instead of created as needed.

func NewHTTPClient

func NewHTTPClient(cfg HTTPConfig) (*HTTPClient, error)

NewHTTPClient creates an HTTPClient using the specified configurations.

func (*HTTPClient) Do

func (hc *HTTPClient) Do(req *http.Request) (*http.Response, error)

Do sends an HTTP request and returns an HTTP response. It implements the RequestExecutor interface.

type HTTPConfig

type HTTPConfig struct {
	// UseHTTPS indicates if HTTPS is used.
	UseHTTPS bool `json:"useHTTPS,omitempty"`

	// ProxyURL specifies an HTTP proxy server URL.
	// If specified, all transports go through the proxy server.
	ProxyURL string `json:"proxyURL,omitempty"`

	// ProxyUsername specifies the username used to authenticate with HTTP proxy
	// server if required.
	ProxyUsername string `json:"proxyUsername,omitempty"`

	// ProxyPassword specifies the password used to authenticate with HTTP proxy
	// server if required.
	ProxyPassword string `json:"proxyPassword,omitempty"`

	// UseProxyFromEnv indicates whether to use the proxy server that is set by
	// the environment variables HTTP_PROXY, HTTPS_PROXY and NO_PROXY
	// (or the lowercase versions thereof).
	// If UseProxyFromEnv is true, it takes precedence over the ProxyURL
	// parameter.
	UseProxyFromEnv bool `json:"useProxyFromEnv,omitempty"`

	// MaxIdleConns controls the maximum number of idle (keep-alive) connections
	// across all hosts.
	// The default value is 100.
	MaxIdleConns int `json:"maxIdleConns,omitempty"`

	// MaxIdleConnsPerHost controls the maximum idle (keep-alive) connections
	// to keep per-host.
	// The default value is 100.
	MaxIdleConnsPerHost int `json:"maxIdleConnsPerHost,omitempty"`

	// IdleConnTimeout is the maximum amount of time an idle (keep-alive)
	// connection will remain idle before closing itself.
	// The default is 90 seconds.
	IdleConnTimeout time.Duration `json:"idleConnTimeout,omitempty"`

	// SslSessionTimeout is the timeout value for an SSL session.
	// The default is 30 seconds.
	SslSessionTimeout time.Duration `json:"sslSessionTimeout,omitempty"`

	// InsecureSkipVerify controls whether a client verifies the server's
	// certificate chain and host name.
	// If InsecureSkipVerify is true, TLS accepts any certificate presented by
	// the server and any host name in that certificate.
	// In this mode, TLS is susceptible to man-in-the-middle attacks.
	InsecureSkipVerify bool `json:"insecureSkipVerify,omitempty"`

	// CertPath specifies the path to a pem-encoded certificate file.
	// Certificates in this file will be used in addition to system certificates.
	// This field is typically used for local self-signed certificates.
	// If InsecureSkipVerify is true, this field is ignored.
	CertPath string `json:"certPath,omitempty"`

	// ServerName is used to verify the hostname for self-signed certificates.
	// This field is only used if CertPath is nonempty, and is typically set
	// to the "CN" subject value from the certificate specified by CertPath.
	// If InsecureSkipVerify is true, this field is ignored.
	ServerName string `json:"serverName,omitempty"`
}

HTTPConfig contains parameters used to configure HTTPClient.

type RequestExecutor

type RequestExecutor interface {
	// Do is used to send an http request to server, returns an http response
	// and an error if occurred during execution.
	Do(req *http.Request) (*http.Response, error)
}

RequestExecutor represents an interface used to execute an HTTP request.

type Response

type Response struct {
	Body []byte // HTTP response body.
	Code int    // HTTP response status code.
}

Response represents a response that contains the content and status code of an http.Response returned from server.

func DoRequest

func DoRequest(ctx context.Context, executor RequestExecutor, timeout time.Duration,
	method string, url string, data []byte, headers map[string]string,
	logger *logger.Logger) (*Response, error)

DoRequest creates an http request using the specified method, url, data and headers, then executes the request using the specified executor. When executor returns an http response after execution, DoRequest checks the response status code, it returns immediately if status code is less than 500, otherwise, it retries the request until either the request gets executed successfully or the specified timeout elapses.

Jump to

Keyboard shortcuts

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