Documentation ¶
Index ¶
- Constants
- Variables
- func CtxWithVar(ctx context.Context, name, value string) context.Context
- func CtxWithVars(ctx context.Context, vars Vars) context.Context
- type CapturingSender
- type HandlerFunc
- type JSONErrorHandler
- type JSONErrorResponse
- type JSONHandlerFunc
- type JSONRequest
- type JSONResourceHandler
- type JSONResponse
- type JSONRouter
- func (j *JSONRouter) Handle(path string, handler JSONHandlerFunc, methods ...string) *RouteHandler
- func (j *JSONRouter) HandleResource(name string, handler JSONResourceHandler) []*RouteHandler
- func (j *JSONRouter) HandleWithCode(path string, handler JSONHandlerFunc, okCode int, methods ...string) *RouteHandler
- func (j *JSONRouter) Subroute(path string) *JSONRouter
- func (j *JSONRouter) SubrouteWithErrorHandler(path string, errHandler JSONErrorHandler) *JSONRouter
- func (j *JSONRouter) WrapHandlerFunc(handler JSONHandlerFunc, okCode int) HandlerFunc
- type MiddlewareFunc
- func NewCapturingMiddleware(f func(ctx context.Context, r *backend.CallResourceRequest, n NextFunc)) MiddlewareFunc
- func NewLoggingMiddleware(logger logging.Logger) MiddlewareFunc
- func NewMetricsMiddleware(cfg metrics.Config, registerer prometheus.Registerer) MiddlewareFunc
- func NewTracingMiddleware(tracer trace.Tracer) MiddlewareFunc
- type NextFunc
- type ResourceGroupRouter
- type RouteHandler
- type RouteInfo
- type Router
- func (r *Router) CallResource(ctx context.Context, req *backend.CallResourceRequest, ...) error
- func (r *Router) Handle(path string, handler HandlerFunc, methods ...string) *RouteHandler
- func (r *Router) ListenAndServe() error
- func (r *Router) RouteByName(name string) *RouteHandler
- func (r *Router) Subrouter(path string) *Subrouter
- func (r *Router) Use(middlewares ...middleware)
- type Store
- type Subrouter
- type Vars
Constants ¶
const (
// ContentTypeJSON is the content-type header value for JSON content.
ContentTypeJSON = "application/json"
)
const (
// HeaderContentType is the header key for content type.
HeaderContentType = "Content-Type"
)
Variables ¶
var BodySizeBuckets = []float64{1 * mb, 2.5 * mb, 5 * mb, 10 * mb, 25 * mb, 50 * mb, 100 * mb, 250 * mb}
Functions ¶
func CtxWithVar ¶
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.
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 ¶
func (c *CapturingSender) Send(res *backend.CallResourceResponse) error
Send captures the response res.
type HandlerFunc ¶
type HandlerFunc func(context.Context, *backend.CallResourceRequest, backend.CallResourceResponseSender)
HandlerFunc defines the signatures handlers need to have in order to be used in this router.
var DefaultNotFoundHandler HandlerFunc = func( _ 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 ¶
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 ¶
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 (*Router) CallResource ¶
func (r *Router) CallResource( ctx context.Context, req *backend.CallResourceRequest, sender backend.CallResourceResponseSender, ) error
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 ¶
ListenAndServe hooks into the backend of the plugin SDK to handle and serve resource API requests nolint: staticcheck TODO: migration to backend.Manage requires plugin ID
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.
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 string, options resource.StoreListOptions) (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.
type Vars ¶
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 VarsFromCtx ¶
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.