rest

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 22, 2018 License: Apache-2.0 Imports: 12 Imported by: 0

README

HTTPmux

The REST Plugin is a infrastructure Plugin which allows app plugins to handle HTTP requests (see the diagram below) in this sequence:

  1. httpmux starts the HTTP server in its own goroutine
  2. Plugins register their handlers with REST Plugin. To service HTTP requests, a plugin must first implement a handler function and register it at a given URL path using the RegisterHTTPHandler method. REST Plugin uses an HTTP request multiplexer from the gorilla/mux package to register the HTTP handlers by the specified URL path.
  3. HTTP server routes HTTP requests to their respective registered handlers using the gorilla/mux multiplexer.

http

Configuration

  • the server's port can be defined using commandline flag http-port or via the environment variable HTTP_PORT.

Example

The following example demonstrates the usage of the REST Plugin plugin API:

// httpExampleHandler returns a very simple HTTP request handler.
func httpExampleHandler(formatter *render.Render) http.HandlerFunc {

    // An example HTTP request handler which prints out attributes of 
    // a trivial Go structure in JSON format.
    return func(w http.ResponseWriter, req *http.Request) {
        formatter.JSON(w, http.StatusOK, struct{ Example string }{"This is an example"})
    }
}

// Register our HTTP request handler as a GET method serving at 
// the URL path "/example".
httpmux.RegisterHTTPHandler("/example", httpExampleHandler, "GET")

Once the handler is registered with REST Plugin and the agent is running, you can use curl to verify that it is operating properly:

$ curl -X GET http://localhost:9191/example
{
  "Example": "This is an example"
}

Documentation

Overview

Package rest implements the HTTP server through which plugins can expose their REST APIs to the outside world.

Index

Constants

View Source
const (
	// DefaultHTTPPort is used during HTTP server startup unless different port was configured
	DefaultHTTPPort = "9191"
	// DefaultIP 0.0.0.0
	DefaultIP = "0.0.0.0"
	// DefaultEndpoint 0.0.0.0:9191
	DefaultEndpoint = DefaultIP + ":" + DefaultHTTPPort
)

Variables

This section is empty.

Functions

func DeclareHTTPPortFlag added in v1.0.4

func DeclareHTTPPortFlag(pluginName core.PluginName, defaultPortOpts ...uint)

DeclareHTTPPortFlag declares http port (with usage & default value) a flag for a particular plugin name

func FixConfig added in v1.0.4

func FixConfig(cfg *Config)

FixConfig fill default values for empty fields

func ListenAndServeHTTP

func ListenAndServeHTTP(config Config, handler http.Handler) (httpServer io.Closer, err error)

ListenAndServeHTTP starts a http server.

func PluginConfig added in v1.0.4

func PluginConfig(pluginCfg config.PluginConfig, cfg *Config, pluginName core.PluginName) error

PluginConfig tries : - to load flag <plugin-name>-port and then FixConfig() just in case - alternatively <plugin-name>-config and then FixConfig() just in case - alternatively DefaultConfig()

Types

type Config

type Config struct {
	// Endpoint is an address of HTTP server
	Endpoint string

	// ReadTimeout is the maximum duration for reading the entire
	// request, including the body.
	//
	// Because ReadTimeout does not let Handlers make per-request
	// decisions on each request body's acceptable deadline or
	// upload rate, most users will prefer to use
	// ReadHeaderTimeout. It is valid to use them both.
	ReadTimeout time.Duration

	// ReadHeaderTimeout is the amount of time allowed to read
	// request headers. The connection's read deadline is reset
	// after reading the headers and the Handler can decide what
	// is considered too slow for the body.
	ReadHeaderTimeout time.Duration

	// WriteTimeout is the maximum duration before timing out
	// writes of the response. It is reset whenever a new
	// request's header is read. Like ReadTimeout, it does not
	// let Handlers make decisions on a per-request basis.
	WriteTimeout time.Duration

	// IdleTimeout is the maximum amount of time to wait for the
	// next request when keep-alives are enabled. If IdleTimeout
	// is zero, the value of ReadTimeout is used. If both are
	// zero, there is no timeout.
	IdleTimeout time.Duration

	// MaxHeaderBytes controls the maximum number of bytes the
	// server will read parsing the request header's keys and
	// values, including the request line. It does not limit the
	// size of the request body.
	// If zero, DefaultMaxHeaderBytes is used.
	MaxHeaderBytes int
}

Config is a configuration for HTTP server It is meant to be extended with security (TLS...)

func DefaultConfig added in v1.0.4

func DefaultConfig() *Config

DefaultConfig returns new instance of config with default endpoint

func (*Config) GetPort added in v1.0.4

func (cfg *Config) GetPort() int

GetPort parses suffix from endpoint & returns integer after last ":" (otherwise it returns 0)

type Deps

type Deps struct {
	Log                 logging.PluginLogger //inject
	PluginName          core.PluginName      //inject
	config.PluginConfig                      //inject
}

Deps lists the dependencies of the Rest plugin.

type ForkDeps added in v1.0.4

type ForkDeps struct {
	// DefaultHTTP is used if there is no different configuration
	DefaultHTTP HTTPHandlers //inject

	Log                 logging.PluginLogger //inject
	PluginName          core.PluginName      //inject
	config.PluginConfig                      //inject
}

ForkDeps lists the dependencies of the Fork on top of Rest plugin.

type ForkPlugin added in v1.0.4

type ForkPlugin struct {
	Deps ForkDeps
	*Config
	// contains filtered or unexported fields
}

ForkPlugin checks the configuration and based on this it delegates API calls to new instance or existing instance of HTTP server

func (*ForkPlugin) AfterInit added in v1.0.4

func (plugin *ForkPlugin) AfterInit() error

AfterInit starts the HTTP server. (only if port was different in Init())

func (*ForkPlugin) Close added in v1.0.4

func (plugin *ForkPlugin) Close() error

Close stops the HTTP server. (only if port was different in Init())

func (*ForkPlugin) GetPort added in v1.0.4

func (plugin *ForkPlugin) GetPort() int

GetPort returns plugin configuration port (delegated call)

func (*ForkPlugin) Init added in v1.0.4

func (plugin *ForkPlugin) Init() (err error)

Init checks config if the port is different that it creates ne HTTP server

func (*ForkPlugin) RegisterHTTPHandler added in v1.0.4

func (plugin *ForkPlugin) RegisterHTTPHandler(path string,
	handler func(formatter *render.Render) http.HandlerFunc,
	methods ...string) *mux.Route

RegisterHTTPHandler registers HTTP <handler> at the given <path>. (delegated call)

func (*ForkPlugin) String added in v1.0.4

func (plugin *ForkPlugin) String() string

String returns plugin name (if not set defaults to "HTTP-FORK")

type HTTPHandlers

type HTTPHandlers interface {
	// RegisterHTTPHandler propagates to Gorilla mux
	RegisterHTTPHandler(path string,
		handler func(formatter *render.Render) http.HandlerFunc,
		methods ...string) *mux.Route

	// GetPort returns configured port number (for debugging purposes)
	GetPort() int
}

HTTPHandlers defines the API exposed by the REST plugin. Use this interface to declare dependency on the REST functionality, i.e.:

type Deps struct {
    HTTP rest.HTTPHandlers // inject plugin implementing RegisterHTTPHandler
    // other dependencies ...
}

type ListenAndServe

type ListenAndServe func(config Config, handler http.Handler) (
	httpServer io.Closer, err error)

ListenAndServe is a function that uses <config> & <handler> to handle HTTP Requests. It return an instance of io.Closer to close the HTTP Server during cleanup.

type Plugin

type Plugin struct {
	Deps
	*Config
	// contains filtered or unexported fields
}

Plugin struct holds all plugin-related data.

func FromExistingServer

func FromExistingServer(listenAndServe ListenAndServe) *Plugin

FromExistingServer is used mainly for testing purposes

Example:

   httpmux.FromExistingServer(mock.SetHandler)
	  mock.NewRequest("GET", "/v1/a", nil)

func (*Plugin) AfterInit

func (plugin *Plugin) AfterInit() (err error)

AfterInit starts the HTTP server.

func (*Plugin) Close

func (plugin *Plugin) Close() error

Close stops the HTTP server.

func (*Plugin) GetPort added in v1.0.4

func (plugin *Plugin) GetPort() int

GetPort returns plugin configuration port

func (*Plugin) Init

func (plugin *Plugin) Init() (err error)

Init is the plugin entry point called by Agent Core - It prepares Gorilla MUX HTTP Router

func (*Plugin) RegisterHTTPHandler

func (plugin *Plugin) RegisterHTTPHandler(path string,
	handler func(formatter *render.Render) http.HandlerFunc,
	methods ...string) *mux.Route

RegisterHTTPHandler registers HTTP <handler> at the given <path>.

func (*Plugin) String added in v1.0.4

func (plugin *Plugin) String() string

String returns plugin name (if not set defaults to "HTTP")

Directories

Path Synopsis
Package mock implements a mock HTTP server.
Package mock implements a mock HTTP server.

Jump to

Keyboard shortcuts

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