consul

package module
Version: v2.0.1+incompatible Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2017 License: MIT Imports: 8 Imported by: 0

README

gentleman-consul Build Status GoDoc Coverage Status Go Report Card

gentleman's v2 plugin for easy service discovery using Consul.

Provides transparent retry/backoff support for resilient and reactive HTTP client capabilities.
It also allows you to use custom retry strategies, such as constant or exponential retries.

Installation

go get -u gopkg.in/h2non/gentleman-consul.v2

Versions

  • v1 - First version, uses gentleman@v1.
  • v2 - Latest version, uses gentleman@v2.

API

See godoc reference for detailed API documentation.

Examples

See examples directory for featured examples.

Simple request
package main

import (
  "fmt"

  "gopkg.in/h2non/gentleman.v2"
	"gopkg.in/h2non/gentleman-consul.v2"
)

func main() {
  // Create a new client
  cli := gentleman.New()

  // Register Consul's plugin at client level
  cli.Use(consul.New(consul.NewConfig("demo.consul.io", "web")))

  // Create a new request based on the current client
  req := cli.Request()

  // Set a new header field
  req.SetHeader("Client", "gentleman")

  // Perform the request
  res, err := req.Send()
  if err != nil {
    fmt.Printf("Request error: %s\n", err)
    return
  }
  if !res.Ok {
    fmt.Printf("Invalid server response: %d\n", res.StatusCode)
    return
  }

  // Print response info
  fmt.Printf("Server URL: %s\n", res.RawRequest.URL.String())
  fmt.Printf("Response status: %d\n", res.StatusCode)
  fmt.Printf("Server header: %s\n", res.Header.Get("Server"))
}
Custom retry strategy
package main

import (
  "fmt"
	"time"

	"gopkg.in/h2non/gentleman.v2"
	"gopkg.in/h2non/gentleman-consul.v1"
	"gopkg.in/eapache/go-resiliency.v1/retrier"
)

func main() {
  // Create a new client
  cli := gentleman.New()

  // Configure Consul plugin
  config := consul.NewConfig("demo.consul.io", "web")

  // Use a custom retrier strategy with max 10 retry attempts
  config.Retrier = retrier.New(retrier.ConstantBackoff(10, time.Duration(25*time.Millisecond)), nil)

  // Register Consul's plugin at client level
  cli.Use(consul.New(config))

  // Create a new request based on the current client
  req := cli.Request()

  // Set a new header field
  req.SetHeader("Client", "gentleman")

  // Perform the request
  res, err := req.Send()
  if err != nil {
    fmt.Printf("Request error: %s\n", err)
    return
  }
  if !res.Ok {
    fmt.Printf("Invalid server response: %d\n", res.StatusCode)
    return
  }

  // Print response info
  fmt.Printf("Server URL: %s\n", res.RawRequest.URL.String())
  fmt.Printf("Response status: %d\n", res.StatusCode)
  fmt.Printf("Server header: %s\n", res.Header.Get("Server"))
}

License

MIT - Tomas Aparicio

Documentation

Index

Constants

View Source
const Version = "2.0.1"

Version defines the package semantic version

Variables

View Source
var CacheTTL = 10 * time.Minute

CacheTTL stores the default Consul catalog refresh cycle TTL. Default to 10 minutes.

View Source
var DefaultConfig = api.DefaultConfig

DefaultConfig provides a custom

View Source
var DefaultRetrier = retry.ConstantBackoff

DefaultRetrier stores the default retry strategy used by the plugin. By default will use a constant retry strategy with a maximum of 3 retry attempts.

View Source
var Scheme = "http"

Scheme represents the URI scheme used by default.

Functions

func New

func New(config *Config) plugin.Plugin

New creates a new Consul client with the given config and returns the gentleman plugin.

Types

type Config

type Config struct {
	// Retry enables/disables HTTP request retry policy. Defaults to true.
	Retry bool

	// Cache enables/disables the Consul catalog internal cache
	// avoiding recurrent request to Consul server.
	Cache bool

	// Service stores the Consul's service name identifier. E.g: web.
	Service string

	// Tag stores the optional Consul's service tag to use when asking to Consul server.
	Tag string

	// Scheme stores the default HTTP URI scheme to be used when asking to Consul server.
	// Defaults to: http.
	Scheme string

	// Retrier stores the retry strategy to be used.
	// Defaults to: ContanstBackOff with max 3 retries.
	Retrier retry.Retrier

	// CacheTTL stores the max Consul catalog cache TTL.
	CacheTTL time.Duration

	// Client stores the official Consul client Config instance.
	Client *api.Config

	// Query stores the official Consul client query options when asking to Consul server.
	Query *api.QueryOptions
}

Config represents the plugin supported settings.

func NewBasicConfig

func NewBasicConfig(server string) *Config

NewBasicConfig creates a new basic default config with the given Consul server hostname.

func NewConfig

func NewConfig(server, service string) *Config

NewConfig creates a new plugin with default settings and custom Consul server URL and service name.

type Consul

type Consul struct {
	// mutex is used internallt to avoid race coditions for multithread scenarios.
	sync.Mutex

	// Config stores the Consul's plugin specific settings.
	Config *Config

	// Client stores the official Consul client.
	Client *api.Client
	// contains filtered or unexported fields
}

Consul represents the Consul plugin adapter for gentleman, which encapsulates the official Consul client and plugin specific settings.

func NewClient

func NewClient(config *Config) *Consul

NewClient creates a new Consul high-level client.

func (*Consul) GetBestCandidateNode

func (c *Consul) GetBestCandidateNode(ctx *context.Context) (string, error)

GetBestCandidateNode retrieves and returns the best service node candidate asking to Consul server catalog or reading catalog from cache.

func (*Consul) GetNodes

func (c *Consul) GetNodes() ([]string, error)

GetNodes returns a list of nodes for the current service from Consul server or from cache (if enabled and not expired).

func (*Consul) IsUpdated

func (c *Consul) IsUpdated() bool

IsUpdated returns true if the current list of catalog services is up-to-date, based on the cache TTL.

func (*Consul) OnBeforeDial

func (c *Consul) OnBeforeDial(ctx *context.Context, h context.Handler)

OnBeforeDial is a middleware function handler that replaces the outgoing request URL and provides a new http.RoundTripper if necessary in order to handle request failures and retry it accordingly.

func (*Consul) Plugin

func (c *Consul) Plugin() plugin.Plugin

Plugin returns the gentleman plugin to be plugged.

func (*Consul) SetServerURL

func (c *Consul) SetServerURL(ctx *context.Context, host string)

SetServerURL sets the request URL fields based on the given Consul service instance.

func (*Consul) UpdateCache

func (c *Consul) UpdateCache(nodes []string)

UpdateCache updates the list of catalog services.

func (*Consul) UseBestCandidateNode

func (c *Consul) UseBestCandidateNode(ctx *context.Context) error

UseBestCandidateNode sets the best service node URL in the given gentleman context.

type Retrier

type Retrier struct {
	// Consul stores the Consul client wrapper instance.
	Consul *Consul

	// Context stores the HTTP current gentleman context.
	Context *context.Context

	// Retry stores the retry strategy to be used.
	Retry retry.Retrier
}

Retrier provides a retry.Retrier capable interface that encapsulates Consul client and user defined strategy.

func NewRetrier

func NewRetrier(c *Consul, ctx *context.Context) *Retrier

NewRetrier creates a default retrier for the given Consul client and context.

func (*Retrier) Run

func (r *Retrier) Run(fn func() error) error

Run runs the given function multiple times, acting like a proxy to user defined retry strategy.

Directories

Path Synopsis
_examples

Jump to

Keyboard shortcuts

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