envoy

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: May 3, 2024 License: MIT Imports: 19 Imported by: 0

README

Simplified Go interface for HTTP Golang Filter on Envoy Proxy

Go Reference Go Report Card Test Codecov

A simplified interface for building plugin on Envoy Proxy with HTTP Golang Filter.

Features

Installation

go get github.com/ardikabs/go-envoy

Development Guide

Prerequisites
Setup
  • Install Git.

  • Install Go 1.20.

  • Clone the project.

    $ git clone -b plugin git@github.com:ardkabs/go-envoy.git
    
  • Create a meaningful branch

    $ git checkout -b <your-meaningful-branch>
    
  • Test your changes.

    $ make test
    
  • We highly recommend instead of only run test, please also do audit which include formatting, linting, vetting, and testing.

    $ make audit
    
  • Add, commit, and push changes to repository

    $ git add .
    $ git commit -s -m "<conventional commit style>"
    $ git push origin <your-meaningful-branch>
    

    For writing commit message, please use conventionalcommits as a reference.

  • Create a Pull Request (PR). In your PR's description, please explain the goal of the PR and its changes.

Testing
Unit Test
$ make test
Try It

To try this interface in action, heads to example directory.

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ResponseUnauthorized        = NewMinimalJSONResponse("UNAUTHORIZED", "UNAUTHORIZED")
	ResponseForbidden           = NewMinimalJSONResponse("FORBIDDEN", "FORBIDDEN")
	ResponseTooManyRequest      = NewMinimalJSONResponse("TOO_MANY_REQUEST", "TOO_MANY_REQUEST")
	ResponseInternalServerError = NewMinimalJSONResponse("RUNTIME_ERROR", "RUNTIME_ERROR")
	ResponseServiceUnavailable  = NewMinimalJSONResponse("SERVICE_UNAVAILABLE", "SERVICE_UNAVAILABLE")
)
View Source
var (
	ResponseCodeDetailPrefix_Info         = ResponseCodeDetailPrefix("goext_info")
	ResponseCodeDetailPrefix_Unauthorized = ResponseCodeDetailPrefix("goext_unauthorized")
	ResponseCodeDetailPrefix_AccessDenied = ResponseCodeDetailPrefix("goext_access_denied")
	ResponseCodeDetailPrefix_Error        = ResponseCodeDetailPrefix("goext_error")

	DefaultResponseCodeDetails = ResponseCodeDetailPrefix_Info.Wrap("via_Go_extension")
)

Functions

func CastTo added in v0.1.1

func CastTo(target interface{}, value interface{}) bool

func Clone added in v0.2.0

func Clone(in interface{}) interface{}

Clone create new object from source object, copying only the exported fields.

func DefaultErrorHandler

func DefaultErrorHandler(ctx Context, err error) api.StatusType

func DefaultRender added in v0.1.1

func DefaultRender(keysAndValues []interface{}) []interface{}

DefaultRender supports logr.Marshaler and fmt.Stringer.

func MustGetProperty added in v0.2.0

func MustGetProperty(c Context, name, defaultVal string) string

MustGetProperty is an extended of GetProperty, only panic if value is not in acceptable format.

func NewGatewayHeaders added in v0.2.0

func NewGatewayHeaders(keysAndValues ...string) http.Header

func NewGatewayHeadersWithEnvoyHeader added in v0.2.0

func NewGatewayHeadersWithEnvoyHeader(envoyheader Header, keysAndValues ...string) http.Header

func NewLogger added in v0.1.1

func NewLogger(callback api.FilterCallbacks) logr.Logger

func NewMinimalJSONResponse added in v0.2.0

func NewMinimalJSONResponse(code, message string, errs ...error) []byte

func ReplaceAllEmptySpace added in v0.2.0

func ReplaceAllEmptySpace(s string) string

func RunHttpFilter added in v0.2.0

func RunHttpFilter(filter HttpFilter, cfg interface{})

func ToFlatHeader

func ToFlatHeader(header http.Header) map[string]string

Types

type BufferWriter added in v0.2.0

type BufferWriter interface {
	io.Writer

	WriteString(s string) (n int, err error)
	Bytes() []byte
	String() string
}

type Configuration added in v0.2.0

type Configuration interface {
	GetFilterConfig() interface{}
	GetConfigCallbacks() api.ConfigCallbacks

	// Store allows you to save a value of any type under a key of any type,
	// It designed for sharing data throughout the lifetime of Envoy.
	//
	// Please be cautious! The Store function overwrites any existing data.
	Store(key any, value any)

	// Load retrieves a value associated with a specific key and assigns it to the receiver.
	// It designed for sharing data throughout the lifetime of Envoy.
	//
	// It returns true if a compatible value is successfully loaded,
	// and false if no value is found or an error occurs during the process.
	Load(key any, receiver interface{}) (ok bool, err error)
	// contains filtered or unexported methods
}

type Context

type Context interface {
	// RequestHeader provides an interface to access and modify HTTP Request header, including
	// add, overwrite, or delete existing header.
	// RequestHeader will panic when it used without initializing the request header map first.
	//
	RequestHeader() Header

	// ResponseHeader provides an interface to access and modify HTTP Response header, including
	// add, overwrite, or delete existing header.
	// ResponseHeader will panic when it used without initializing the response header map first.
	//
	ResponseHeader() Header

	// RequestBodyWriter provides an interface for interacting and modifying HTTP Request body.
	//
	RequestBodyWriter() BufferWriter

	// ResponseBodyWriter provides an interface for interacting and modifying HTTP Response body.
	//
	ResponseBodyWriter() BufferWriter

	// Request returns an http.Request struct, which is a read-only data.
	// Attempting to modify this value will have no effect.
	// To make modifications to the request header, please use the RequestHeader() method instead.
	Request() *http.Request

	// Response returns an http.Response struct, which is a read-only data.
	// It means, update anything to this value will result nothing.
	// To make modifications to the response header, please use the ResponseHeader() method instead.
	// To make modifications to the response body, please use the BufferWriter() method instead.
	Response() *http.Response

	// SetRequestHeader is a low-level API, it set request header from RequestHeaderMap interface during DecodeHeaders phase
	SetRequestHeader(api.RequestHeaderMap)

	// SetResponseHeader is a low-level API, it set response header from ResponseHeaderMap interface during EncodeHeaders phase
	SetResponseHeader(api.ResponseHeaderMap)

	// SetRequestBody is a low-level API, it set request body from BufferInstance interface during DecodeData phase
	SetRequestBody(api.BufferInstance)

	// SetResponseBody is a low-level API, it set response body from BufferInstance interface during EncodeData phase
	SetResponseBody(api.BufferInstance)

	// Store allows you to save a value of any type under a key of any type.
	// It is designed for sharing data within a Context.
	// If you wish to share data throughout the lifetime of Envoy,
	// please refer to the Configuration interface.
	//
	// Please be cautious! The Store function overwrites any existing data.
	Store(key any, value any)

	// Load retrieves a value associated with a specific key and assigns it to the receiver.
	// It is designed for sharing data within a Context.
	// If you wish to share data throughout the lifetime of Envoy,
	// please refer to the Configuration interface.
	//
	// It returns true if a compatible value is successfully loaded,
	// and false if no value is found or an error occurs during the process.
	Load(key any, receiver interface{}) (ok bool, err error)

	// Log provides a logger from the plugin to the Envoy Log. It accessible under Envoy `http` component.
	// e.g., Envoy flag `--component-log-level http:{debug,info,warn,error,critical}`
	Log() logr.Logger

	// JSON sends a JSON response with status code.
	JSON(code int, b []byte, headers map[string][]string, opts ...ReplyOption) error

	// String sends a plain text response with status code.
	String(code int, s string, headers map[string][]string, opts ...ReplyOption) error

	// StatusType is a low-level API used to specify the type of status to be communicated to Envoy.
	StatusType() api.StatusType

	// Committed indicates whether the current context has already completed its processing
	// within the plugin and forwarded the result to Envoy.
	Committed() bool

	// StreamInfo offers an interface for retrieving comprehensive details about the incoming HTTP traffic, including
	// information such as the route name, filter chain name, dynamic metadata, and more.
	// It provides direct access to low-level Envoy information, so it's important to use it with a clear understanding of your intent.
	StreamInfo() api.StreamInfo

	// Metrics sets gauge stats that could to record both increase and decrease metric. E.g., current active requests.
	Metrics() Metrics

	// GetProperty is a helper function to fetch Envoy attributes based on https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/advanced/attributes.
	// Currently, it only supports value that has a string format, work in progress for List/Map format.
	GetProperty(name, defaultVal string) (string, error)

	// Configuration returns the filter configuration
	Configuration() Configuration
}

func NewContext added in v0.1.1

func NewContext(cb api.FilterCallbacks, opts ...ContextOption) (Context, error)

type ContextOption added in v0.2.0

type ContextOption func(c *context) error

func WithFilterConfiguration added in v0.2.0

func WithFilterConfiguration(cfg Configuration) ContextOption

type ErrorHandler

type ErrorHandler func(Context, error) api.StatusType

type Handler added in v0.1.1

type Handler func(next HandlerFunc) HandlerFunc

type HandlerFunc added in v0.1.1

type HandlerFunc func(ctx Context) error

func HandlerDecorator added in v0.1.1

func HandlerDecorator(next HandlerFunc) HandlerFunc

type HandlerManager added in v0.1.1

type HandlerManager interface {
	Use(handler Handler)
	Handle(ctx Context) api.StatusType
}

func NewManager added in v0.1.1

func NewManager() HandlerManager

func NewManagerWithErrorHandler added in v0.1.1

func NewManagerWithErrorHandler(errHandler ErrorHandler) HandlerManager
type Header interface {
	api.HeaderMap

	AsMap() map[string][]string
}

type HttpFilter added in v0.2.0

type HttpFilter interface {
	Name() string

	OnStart(c Context)
	Handlers(c Context) []HttpFilterHandler
	OnComplete(c Context)
}

type HttpFilterHandler added in v0.2.0

type HttpFilterHandler interface {
	Disable() bool

	OnRequestHeader(c Context, header http.Header) error
	OnRequestBody(c Context, body []byte) error
	OnResponseHeader(c Context, header http.Header) error
	OnResponseBody(c Context, body []byte) error
}

type Metrics added in v0.2.0

type Metrics interface {
	// Gauge sets gauge statistics that can record both increasing and decreasing metrics. E.g., current active requests.
	Gauge(name string, labelKeyValues ...string) api.GaugeMetric
	// Counter sets counter statistics that only record for increase, but never decrease metrics. E.g., total requests.
	Counter(name string, labelKeyValues ...string) api.CounterMetric
	// Histogram is still a WIP
	Histogram(name string, labelKeyValues ...string) api.HistogramMetric
}

func NewMetrics added in v0.2.0

func NewMetrics(config Configuration) Metrics

type PassthroughHttpFilterHandler added in v0.2.0

type PassthroughHttpFilterHandler struct{}

func (PassthroughHttpFilterHandler) Disable added in v0.2.0

func (PassthroughHttpFilterHandler) OnRequestBody added in v0.2.0

func (PassthroughHttpFilterHandler) OnRequestBody(c Context, body []byte) error

func (PassthroughHttpFilterHandler) OnRequestHeader added in v0.2.0

func (PassthroughHttpFilterHandler) OnRequestHeader(c Context, header http.Header) error

func (PassthroughHttpFilterHandler) OnResponseBody added in v0.2.0

func (PassthroughHttpFilterHandler) OnResponseBody(c Context, body []byte) error

func (PassthroughHttpFilterHandler) OnResponseHeader added in v0.2.0

func (PassthroughHttpFilterHandler) OnResponseHeader(c Context, header http.Header) error

type ReplyOption added in v0.1.1

type ReplyOption func(o *ReplyOptions)

func WithGrpcStatus

func WithGrpcStatus(status int64) ReplyOption

func WithResponseCodeDetails added in v0.1.1

func WithResponseCodeDetails(detail string) ReplyOption

WithResponseCodeDetails sets response code details for a request/response to the envoy context It accepts a string, but commonly for convention purpose please check RespCodeDetails constants.

type ReplyOptions added in v0.1.1

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

func NewDefaultReplyOptions added in v0.2.0

func NewDefaultReplyOptions() *ReplyOptions

type ResponseCodeDetailPrefix added in v0.2.0

type ResponseCodeDetailPrefix string

func (ResponseCodeDetailPrefix) Wrap added in v0.2.0

func (prefix ResponseCodeDetailPrefix) Wrap(message string) string

Wrap wraps message with given response code detail prefix

Directories

Path Synopsis
pkg
test

Jump to

Keyboard shortcuts

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