thc

package module
v0.0.0-...-487a65b Latest Latest
Warning

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

Go to latest
Published: Jun 6, 2018 License: MIT Imports: 12 Imported by: 0

README

THC - Timed HTTP Client for Go

GoDoc Build Status Go Report Card

THC is a thin wrapper around Go's http.Client package which provides the following extra features.

Metrics

THC exports metrics of your requests using expvar. You can observe average times for DNS lookups, TLS handshakes, TCP sessions and more. Look at the documentation for a list of exported metrics.

Circuit breaker

After a defined number of consecutive failures, THC will switch to an out of service state. In this state, the client will stop sending HTTP requests and instead will return the error ErrOutOfService. It is up to the application to decide what to do in that case. After a predefined amount of time, the service will be restores and THC will resume to work normally.

Example

package main

import (
    "net/http"
    "time"

    "github.com/oliwer/thc"
)

var client = &thc.THC{
    Client:      &http.Client{Timeout: 100 * time.Millisecond},
    Name:        "example",
    MaxErrors:   10,
    HealingTime: 20 * time.Second,
}

func init() {
    client.PublishExpvar()
}

func main() {
    for {
        resp, err := client.Get("https://example.com/thing.json")

        if err == thc.ErrOutOfService {
            // The service is down for 20s. (HealingTime)
        }

        if err != nil {
            // There was an error but we are still OK because
            // still under MaxErrors consecutive errors.
        }

        // Process resp normally...
    }
}

Notes

THC requires Go v1.8 or above. It is thread-safe and lock-less.

Documentation

Overview

Package thc is a thin wrapper around Go's http.Client package which provides:

Metrics

THC exports metrics of your requests using expvar. You can observe average times for DNS lookups, TLS handshakes, TCP sessions and more.

Circuit breaker

After a defined number of consecutive failures, THC will switch to an *out of service* state. In this state, the client will stop sending HTTP requests and instead will return the error ErrOutOfService. It is up to the application to decide what to do in that case. After a predefined amount of time, the service will be restored and THC will resume to work normally.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrOutOfService = errors.New("HTTP client out of service")

ErrOutOfService is returned by the client when the maximum number of consecutive errors (MaxErrors) has been attained, and no HTTP request has been performed.

Functions

This section is empty.

Types

type Metrics

type Metrics struct {
	// Time to perform a DNS Lookup.
	DNSLookup *ratecounter.AvgRateCounter
	// Time to open a new TCP connection.
	TCPConnection *ratecounter.AvgRateCounter
	// Time to perform a TLS handshake.
	TLSHandshake *ratecounter.AvgRateCounter

	// Total time to get a ready-to-use connection. This includes the
	// previous 3 metrics. It may be zero if you use a connection pool.
	GetConnection *ratecounter.AvgRateCounter
	// Total time taken to send the HTTP request, including the time
	// to get a connection.
	WriteRequest *ratecounter.AvgRateCounter
	// Total time elapsed until we got the first byte of the response.
	// This includes the previous metric.
	GetResponse *ratecounter.AvgRateCounter

	// Counter indicating how many times per hour was the client out of service.
	OutOfService *ratecounter.RateCounter
}

Metrics exported via expvar. The times are in nanoseconds and are averages per minute.

type THC

type THC struct {
	// The HTTP client to use. Defaults to Go's HTTP client.
	Client *http.Client
	// Name is the prefix used for publishing expvars. Default: "thc".
	Name string
	// Number of errors after which the client becomes out of service.
	// Zero means never. Default: 0.
	MaxErrors int32
	// Lifespan of the out of service state. No HTTP requests are performed
	// in this state. Default: 10s.
	HealingTime time.Duration
	// contains filtered or unexported fields
}

THC - Timed HTTP Client. Implements the same interface as Go's http.Client.

Example
package main

import (
	"net/http"
	"time"

	"github.com/oliwer/thc"
)

var client = &thc.THC{
	Client:      &http.Client{Timeout: 10 * time.Millisecond},
	Name:        "example",
	MaxErrors:   10,
	HealingTime: 20 * time.Second,
}

func init() {
	client.PublishExpvar()
}

func main() {
	for {
		resp, err := client.Get("https://error500.nope/")

		if err == thc.ErrOutOfService {
			// The service is down for 20s. (HealingTime)
			break
		}

		if err != nil {
			// There was an error but we are still OK because
			// still under MaxErrors consecutive errors.
			continue
		}

		// Process resp normally...
		resp.Body.Close()
	}
}
Output:

func (*THC) Do

func (c *THC) Do(req *http.Request) (*http.Response, error)

Do sends an HTTP request and returns an HTTP response, following policy (such as redirects, cookies, auth) as configured on the client.

func (*THC) Get

func (c *THC) Get(url string) (resp *http.Response, err error)

Get issues a GET to the specified URL.

func (*THC) Head

func (c *THC) Head(url string) (resp *http.Response, err error)

Head issues a HEAD to the specified URL.

func (*THC) Post

func (c *THC) Post(url string, contentType string, body io.Reader) (resp *http.Response, err error)

Post issues a POST to the specified URL.

func (*THC) PostForm

func (c *THC) PostForm(url string, data url.Values) (resp *http.Response, err error)

PostForm issues a POST to the specified URL, with data's keys and values URL-encoded as the request body.

func (*THC) PublishExpvar

func (c *THC) PublishExpvar()

PublishExpvar will publish all the metrics for a THC instance. This method should be called from the `init` function in your program.` The metrics' names are prefixed with the Name specified in the THC object. Exported metrics:

<name>-dns-lookup
<name>-tcp-connection
<name>-tls-handshake
<name>-get-connection
<name>-write-request
<name>-get-response
<name>-outofservice

Jump to

Keyboard shortcuts

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