router

package
v0.15.3 Latest Latest
Warning

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

Go to latest
Published: Apr 18, 2024 License: Apache-2.0 Imports: 21 Imported by: 3

Documentation

Index

Constants

View Source
const (
	// ContentTypeJSON is the content-type header value for JSON content.
	ContentTypeJSON = "application/json"
)
View Source
const (
	// HeaderContentType is the header key for content type.
	HeaderContentType = "Content-Type"
)

Variables

View Source
var BodySizeBuckets = []float64{1 * mb, 2.5 * mb, 5 * mb, 10 * mb, 25 * mb, 50 * mb, 100 * mb, 250 * mb}

Functions

func CtxWithVar

func CtxWithVar(ctx context.Context, name, value string) context.Context

CtxWithVar adds new value value with name name to context ctx. If ctx already contains Vars, the value will be appended, otherwise a new Vars will be created, value will be added to it and it will be stored in ctx.

func CtxWithVars

func CtxWithVars(ctx context.Context, vars Vars) context.Context

CtxWithVars adds Vars to context. If Vars already were present in the context they will be overwritten.

Types

type CapturingSender

type CapturingSender struct {
	Response *backend.CallResourceResponse
}

CapturingSender is a backend.CallResourceResponseSender that captures the sent response, allowing other to tweak with it and send it afterwards.

func (*CapturingSender) Send

Send captures the response res.

type HandlerFunc

HandlerFunc defines the signatures handlers need to have in order to be used in this router.

var DefaultNotFoundHandler HandlerFunc = func(
	ctx context.Context, req *backend.CallResourceRequest, sender backend.CallResourceResponseSender,
) {
	_ = sender.Send(&backend.CallResourceResponse{
		Status: http.StatusNotFound,
		Body:   []byte(fmt.Sprintf("no route match for path %s", req.Path)),
	})
}

DefaultNotFoundHandler is the handler that is used for handling requests when a handler can't be found for a given route. This can be overridden in the Router.

type JSONErrorHandler

type JSONErrorHandler func(err plugin.Error) (int, JSONResponse)

JSONErrorHandler is a function that takes an error and transforms it into an HTTP code and JSON response pair. It is used by JSONRouter when processing errors returned by route handlers.

type JSONErrorResponse

type JSONErrorResponse struct {
	Code  int    `json:"code"`
	Error string `json:"error"`
}

JSONErrorResponse is the default response format used to render errors from JSON route handlers.

type JSONHandlerFunc

type JSONHandlerFunc func(context.Context, JSONRequest) (JSONResponse, error)

JSONHandlerFunc is a JSON request handler, that takes a context and request and returns a response or an error. It's valid to return a response and a nil error, an error and a nil response OR a nil response and a nil error. In the latter case the response is interpreted as a successful 204 No Content response.

type JSONRequest

type JSONRequest struct {
	Method  string
	URL     url.URL
	Vars    Vars
	Headers http.Header
	Context backend.PluginContext
	Body    io.Reader
}

JSONRequest is the request that is parsed by JSONRouter and passed to its handlers. It contains all information that is available from the route (e.g. vars) or plugin request or plugin context.

type JSONResourceHandler

type JSONResourceHandler struct {
	Create JSONHandlerFunc
	Read   JSONHandlerFunc
	Update JSONHandlerFunc
	Delete JSONHandlerFunc
	List   JSONHandlerFunc
}

JSONResourceHandler is a resource handler that uses the following routing convention:

* GET "/{name}" - `List` all resources "name" * POST "/{name}" - `Create` a new resource "name" * GET "/{name}/{id}" - `Read` a resource "name" with id "id" * PUT "/{name}/{id}" - `Update` a resource "name" with id "id" * DELETE "/{name}/{id}" - `Delete` a resource "name" with id "id"

type JSONResponse

type JSONResponse any

JSONResponse is the response that is returned by JSONRouter handlers. It is serialized to JSON by the router and sent to the requester. Therefore the response must be a JSON-marshalable value, or nil.

type JSONRouter

type JSONRouter struct {
	*Subrouter
	// contains filtered or unexported fields
}

JSONRouter is a router that assumes that responses are JSON-encoded messages and errors carry response codes. JSON router will automatically serialize responses to JSON and send them to the requester, or send back erroneous responses with codes passed in the error (or fall back to 500 if no code is found). For errors it will return a JSON response with error code and err.Error() message. For 500 errors the message will be a generic "internal server error" message.

func NewJSONRouter

func NewJSONRouter() *JSONRouter

NewJSONRouter returns a new JSONRouter with a logger.

func NewJSONRouterWithErrorHandler

func NewJSONRouterWithErrorHandler(errHandler JSONErrorHandler) *JSONRouter

NewJSONRouterWithErrorHandler returns a new JSONRouter with a logger and a custom error handler.

func (*JSONRouter) Handle

func (j *JSONRouter) Handle(path string, handler JSONHandlerFunc, methods ...string) *RouteHandler

Handle attaches a new handler to the route with path and methods methods. If no methods are specified, GET will be used instead.

func (*JSONRouter) HandleResource

func (j *JSONRouter) HandleResource(name string, handler JSONResourceHandler) []*RouteHandler

HandleResource creates routes for a CRUD resource handler handler for a resource name. For all successful requests it will return 200 OK, except for Create route, which will return 201, and Delete route which will always discard responses (so your handler doesn't have to return one) and return 204.

func (*JSONRouter) HandleWithCode

func (j *JSONRouter) HandleWithCode(path string, handler JSONHandlerFunc, okCode int, methods ...string) *RouteHandler

HandleWithCode works like Handle but allows specifying the response code that's returned for successful requests.

func (*JSONRouter) Subroute

func (j *JSONRouter) Subroute(path string) *JSONRouter

Subroute creates a new JSONRouter with all routes prefixed by path.

func (*JSONRouter) SubrouteWithErrorHandler

func (j *JSONRouter) SubrouteWithErrorHandler(path string, errHandler JSONErrorHandler) *JSONRouter

SubrouteWithErrorHandler creates a new JSONRouter with all routes prefixed by path, and overrides the router error handler with given one.

func (*JSONRouter) WrapHandlerFunc

func (j *JSONRouter) WrapHandlerFunc(handler JSONHandlerFunc, okCode int) HandlerFunc

WrapHandlerFunc wraps a JSONHandlerFunc and returns a regular HandlerFunc. The wrapper will take care of parsing the request and handling the response. `okCode` will be used for successful response codes.

type MiddlewareFunc

type MiddlewareFunc func(HandlerFunc) HandlerFunc

MiddlewareFunc is a function that receives a HandlerFunc and returns another HandlerFunc. This allows one to intercept incoming request, before and after the actual handler execution.

func NewCapturingMiddleware

func NewCapturingMiddleware(f func(ctx context.Context, r *backend.CallResourceRequest, n NextFunc)) MiddlewareFunc

NewCapturingMiddleware creates a middleware that allows one to add behavior that affects both the request and the response of the call.

func NewLoggingMiddleware

func NewLoggingMiddleware(logger logging.Logger) MiddlewareFunc

NewLoggingMiddleware returns a MiddleWareFunc which logs an INFO level message for each request, and injects the provided Logger into the context used downstream.

func NewMetricsMiddleware

func NewMetricsMiddleware(cfg metrics.Config, registerer prometheus.Registerer) MiddlewareFunc

func NewTracingMiddleware

func NewTracingMiddleware(tracer trace.Tracer) MiddlewareFunc

NewTracingMiddleware returns a MiddlewareFunc which adds a tracing span for every request which lasts the duration of the request's handle time and includes all attributes which are a part of OpenTelemetry's Semantic Conventions for HTTP spans: https://github.com/open-telemetry/semantic-conventions/blob/main/docs/http/http-spans.md

func (MiddlewareFunc) Middleware

func (m MiddlewareFunc) Middleware(handler HandlerFunc) HandlerFunc

Middleware allows MiddlewareFunc to implement the middleware interface.

type NextFunc

type NextFunc func(ctx context.Context) *backend.CallResourceResponse

NextFunc is the main function to call the downstream middleware when using a capturing middleware.

type ResourceGroupRouter

type ResourceGroupRouter struct {
	*JSONRouter
	// contains filtered or unexported fields
}

ResourceGroupRouter is a Router which exposes generic CRUD routes for every resource contained in a given group.

func NewResourceGroupRouter

func NewResourceGroupRouter(
	resourceGroup resource.KindCollection,
	namespace string,
	clientGenerator resource.ClientGenerator,
) (*ResourceGroupRouter, error)

NewResourceGroupRouter returns a new ResourceGroupRouter, exposing CRUD routes to manipulate resources in given group.

func NewResourceGroupRouterWithStore

func NewResourceGroupRouterWithStore(
	resourceGroup resource.KindCollection,
	namespace string,
	store Store,
) (*ResourceGroupRouter, error)

NewResourceGroupRouterWithStore returns a new ResourceGroupRouter with pre-configured Store.

type RouteHandler

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

RouteHandler is a Handler function assigned to a route

func (*RouteHandler) Methods

func (h *RouteHandler) Methods(methods []string) *RouteHandler

Methods sets the methods the handler function will be called for

func (*RouteHandler) Name

func (h *RouteHandler) Name(name string) *RouteHandler

Name sets the name of the RouteHandler. Names should be unique for retrieval purposes, but uniqueness is not enforced.

type RouteInfo

type RouteInfo struct {
	// Name is the user-provided name on the route, if a name was provided
	Name string
	// Path is the matched route path, as provided by the user when adding the route to the router
	Path string
	// Method is the matched route method
	Method string
}

RouteInfo stores information about a matched route

func MatchedRouteFromContext

func MatchedRouteFromContext(ctx context.Context) RouteInfo

MatchedRouteFromContext returns the RouteInfo set in the request context by the router

type Router

type Router struct {
	// Handler called when there's no route match.
	NotFoundHandler HandlerFunc
	// contains filtered or unexported fields
}

Router is a simple request router specific to the grafana plugin SDK backend.CallResourceRequest HTTP calls. It allows the user to treat the grafana plugin backend as a traditional HTTP server, registering routes and using path parameters as normal.

func NewRouter

func NewRouter() *Router

NewRouter returns a new Router

func (*Router) CallResource

CallResource implements backend.CallResourceHandler, allowing the Router to route resource API requests

func (*Router) Handle

func (r *Router) Handle(path string, handler HandlerFunc, methods ...string) *RouteHandler

Handle registers a handler to a given path and method(s). If no method(s) are specified, GET is implicitly used.

func (*Router) ListenAndServe

func (r *Router) ListenAndServe() error

ListenAndServe hooks into the backend of the plugin SDK to handle and serve resource API requests

func (*Router) RouteByName

func (r *Router) RouteByName(name string) *RouteHandler

RouteByName gets a RouteHandler by its name, if assigned. If multiple routes have the same name, the first registered one will be returned.

func (*Router) Subrouter

func (r *Router) Subrouter(path string) *Subrouter

Subrouter creates and returns a Subrouter for the given path prefix. All handlers registered with the Subrouter will have the prefix added implicitly.

func (*Router) Use

func (r *Router) Use(middlewares ...middleware)

Use adds middlewares to the router.

type Store

type Store interface {
	Add(ctx context.Context, obj resource.Object) (resource.Object, error)
	Get(ctx context.Context, kind string, identifier resource.Identifier) (resource.Object, error)
	List(ctx context.Context, kind, namespace string, filters ...string) (resource.ListObject, error)
	Update(ctx context.Context, obj resource.Object) (resource.Object, error)
	Delete(ctx context.Context, kind string, identifier resource.Identifier) error
}

Store is the interface for a CRD storage component.

type Subrouter

type Subrouter struct {
	Router
	// contains filtered or unexported fields
}

Subrouter is a slightly-extended router meant for being registered a with Subrouter() on either a Router or Subrouter.

func (*Subrouter) Path

func (r *Subrouter) Path() string

type Vars

type Vars map[string]string

Vars is a mapping of string keys to string values, which holds variables captured from the route. e.g. if the route was defined as "/foo/{id}/bar", Vars will contains a key with "id" and value passed in the actual URL.

func NewVars

func NewVars(from map[string]string) Vars

NewVars returns a new empty Vars.

func VarsFromCtx

func VarsFromCtx(ctx context.Context) Vars

VarsFromCtx returns Vars that have been set in the context.Context provided. If there were no Vars in the context a new, empty Vars is returned.

func (Vars) Add

func (v Vars) Add(k, s string) Vars

Add adds a new value s with key k to Vars.

func (Vars) Get

func (v Vars) Get(k string) (string, bool)

Get gets the value with key k. It returns an extra value which indicates whether the value was present in Vars. If Vars are empty, the value is not present or is an empty string, the second return value will be false.

func (Vars) MustGet

func (v Vars) MustGet(k string) string

MustGet behaves like Get but panics if the value is missing.

Jump to

Keyboard shortcuts

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