package
2.7.11
Repository: https://github.com/influxdata/influxdb.git
Documentation: pkg.go.dev

# README

HTTP Handler Style Guide

HTTP Handler

  • Each handler should implement http.Handler
    • This can be done by embedding a httprouter.Router (a light weight HTTP router that supports variables in the routing pattern and matches against the request method)
  • Required services should be exported on the struct
// ThingHandler represents an HTTP API handler for things.
type ThingHandler struct {
	// embedded httprouter.Router as a lazy way to implement http.Handler
	*httprouter.Router

	ThingService         platform.ThingService
	AuthorizationService platform.AuthorizationService

	Logger               *zap.Logger
}

HTTP Handler Constructor

  • Routes should be declared in the constructor
// NewThingHandler returns a new instance of ThingHandler.
func NewThingHandler() *ThingHandler {
	h := &ThingHandler{
		Router: httprouter.New(),
		Logger: zap.Nop(),
	}

	h.HandlerFunc("POST", "/api/v2/things", h.handlePostThing)
	h.HandlerFunc("GET", "/api/v2/things", h.handleGetThings)

	return h
}

Route handlers (http.HandlerFuncs)

  • Each route handler should have an associated request struct and decode function
  • The decode function should take a context.Context and an *http.Request and return the associated route request struct
type postThingRequest struct {
	Thing *platform.Thing
}

func decodePostThingRequest(ctx context.Context, r *http.Request) (*postThingRequest, error) {
	t := &platform.Thing{}
	if err := json.NewDecoder(r.Body).Decode(t); err != nil {
		return nil, err
	}

	return &postThingRequest{
		Thing: t,
	}, nil
}
  • Route http.HandlerFuncs should separate the decoding and encoding of HTTP requests/response from actual handler logic
// handlePostThing is the HTTP handler for the POST /api/v2/things route.
func (h *ThingHandler) handlePostThing(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	req, err := decodePostThingRequest(ctx, r)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	// Do stuff here
	if err := h.ThingService.CreateThing(ctx, req.Thing); err != nil {
		EncodeError(ctx, err, w)
		return
	}

	if err := encodeResponse(ctx, w, http.StatusCreated, req.Thing); err != nil {
		h.Logger.Info("encoding response failed", zap.Error(err))
		return
	}
}
  • http.HandlerFunc's that require particular encoding of http responses should implement an encode response function

# Packages

Package mocks is a generated GoMock package.

# Functions

CheckError reads the http.Response and returns an error if one exists.
CheckErrorStatus for status and any error in the response.
FormatDuration formats a duration to a string.
GetQueryResponse runs a flux query with common parameters and returns the response from the query service.
GetQueryResponseBody reads the body of a response from some query service.
GetToken will parse the token from http Authorization Header.
HealthHandler returns the status of the process.
InactiveUserError encode a error message and status code for inactive users.
LoggingMW middleware for logging inflight http requests.
NewAPIHandler constructs all api handlers beneath it and returns an APIHandler.
NewAuthenticationHandler creates an authentication handler.
NewAuthorizationBackend returns a new instance of AuthorizationBackend.
NewAuthorizationHandler returns a new instance of AuthorizationHandler.
NewBackupBackend returns a new instance of BackupBackend.
NewBackupHandler creates a new handler at /api/v2/backup to receive backup requests.
NewBaseChiRouter returns a new chi router with a 404 handler, a 405 handler, and a panic handler.
NewCheckBackend returns a new instance of CheckBackend.
NewCheckHandler returns a new instance of CheckHandler.
NewClient returns an http.Client that pools connections and injects a span.
NewConfigHandler creates a handler that will return a JSON object with key/value pairs for the configuration values used during the launcher startup.
NewDeleteBackend returns a new instance of DeleteBackend.
NewDeleteHandler creates a new handler at /api/v2/delete to receive delete requests.
NewDocumentBackend returns a new instance of DocumentBackend.
NewDocumentHandler returns a new instance of DocumentHandler.
NewDocumentService creates a client to connect to Influx via HTTP to manage documents.
NewFluxBackend returns a new instance of FluxBackend.
NewFluxHandler returns a new handler at /api/v2/query for flux queries.
NewFrontEndTask converts a internal task type to a task that we want to display to users.
NewHTTPClient creates a new httpc.Client type.
NewLabelHandler returns a new instance of LabelHandler.
NewNotificationEndpointBackend returns a new instance of NotificationEndpointBackend.
NewNotificationEndpointHandler returns a new instance of NotificationEndpointHandler.
NewNotificationEndpointService constructs a new http NotificationEndpointService.
NewNotificationRuleBackend returns a new instance of NotificationRuleBackend.
NewNotificationRuleHandler returns a new instance of NotificationRuleHandler.
NewNotificationRuleService wraps an httpc.Client in a NotificationRuleService.
NewPlatformHandler returns a platform handler that serves the API and associated assets.
NewResourceListHandler is the HTTP handler for the GET /api/v2/resources route.
NewRestoreBackend returns a new instance of RestoreBackend.
NewRestoreHandler creates a new handler at /api/v2/restore to receive restore requests.
NewRootHandler creates a new handler with the given name and registers any root-level (non-API) routes enabled by the caller.
NewRouter returns a new router with a 404 handler, a 405 handler, and a panic handler.
NewScraperBackend returns a new instance of ScraperBackend.
NewScraperHandler returns a new instance of ScraperHandler.
NewService returns a service that is an HTTP client to a remote.
NewSourceBackend returns a new instance of SourceBackend.
NewSourceHandler returns a new instance of SourceHandler.
NewTaskBackend returns a new instance of TaskBackend.
NewTaskHandler returns a new instance of TaskHandler.
NewTelegrafBackend returns a new instance of TelegrafBackend.
NewTelegrafHandler returns a new instance of TelegrafHandler.
NewTelegrafService is a constructor for a telegraf service.
NewURL concats addr and path.
NewVariableBackend creates a backend used by the variable handler.
NewVariableHandler creates a new VariableHandler.
NewWriteBackend returns a new instance of WriteBackend.
NewWriteHandler creates a new handler at /api/v2/write to receive line protocol.
ParseDuration parses a time duration from a string.
ProbeAuthScheme probes the http request for the requests for token or cookie session.
QueryRequestFromProxyRequest converts a query.ProxyRequest into a QueryRequest.
ReadyHandler is a default readiness handler.
Redoc servers the swagger JSON using the redoc package.
SetToken adds the token to the request.
SimpleQuery runs a flux query with common parameters and returns CSV results.
UnauthorizedError encodes a error message and status code for unauthorized access.
WithMaxBatchSizeBytes configures the maximum size for a (decompressed) points batch allowed by the write handler.
WithResourceHandler registers a resource handler on the APIHandler.

# Constants

Bucket is the http query parameter take either the ID or Name interchangably.
BucketID is the http query parameter to specify an bucket by ID.
DebugPath exposes /debug/pprof for go debugging.
HealthPath exposes the health of the service over /health.
MetricsPath exposes the prometheus metrics over /metrics.
Org is the http query parameter that take either the ID or Name interchangeably.
OrgID is the http query parameter to specify an organization by ID.
ReadyPath exposes the readiness of the service over /ready.

# Variables

DefaultTransport wraps http.DefaultTransport in SpanTransport to inject tracing headers into all outgoing requests.
DefaultTransportInsecure is identical to DefaultTransport, with the exception that tls.Config is configured with InsecureSkipVerify set to true.
errors.
errors.
ErrInvalidDuration is returned when parsing a malformatted duration.

# Structs

APIBackend is all services and associated parameters required to construct an APIHandler.
APIHandler is a collection of all the service handlers.
AuthenticationHandler is a middleware for authenticating incoming requests.
AuthorizationBackend is all services and associated parameters required to construct the AuthorizationHandler.
AuthorizationHandler represents an HTTP API handler for authorizations.
AuthorizationService connects to Influx via HTTP using tokens to manage authorizations.
BackupBackend is all services and associated parameters required to construct the BackupHandler.
BackupHandler is http handler for backup service.
CheckBackend is all services and associated parameters required to construct the CheckBackendHandler.
CheckHandler is the handler for the check service.
TODO(gavincabbage): These structures should be in a common place, like other models, but the common influxdb.Check is an interface that is not appropriate for an API client.
CheckService is a client to interact with the handlers in this package over HTTP.
DeleteBackend is all services and associated parameters required to construct the DeleteHandler.
DeleteHandler receives a delete request with a predicate and sends it to storage.
DeleteRequest is the request send over http to delete points.
DeleteService sends data over HTTP to delete points.
DocumentBackend is all services and associated parameters required to construct the DocumentHandler.
DocumentHandler represents an HTTP API handler for documents.
FluxBackend is all services and associated parameters required to construct the FluxHandler.
FluxHandler implements handling flux queries.
FluxQueryService implements query.QueryService by making HTTP requests to the /api/v2/query API endpoint.
FluxService connects to Influx via HTTP using tokens to run queries.
Handler provides basic handling of metrics, health and debug endpoints.
LabelBackend is all services and associated parameters required to construct label handlers.
LabelHandler represents an HTTP API handler for labels.
LabelService connects to Influx via HTTP using tokens to manage labels.
MemberBackend is all services and associated parameters required to construct member handler.
NoopProxyHandler is a no-op FeatureProxyHandler.
NotificationEndpointBackend is all services and associated parameters required to construct the NotificationEndpointBackendHandler.
NotificationEndpointHandler is the handler for the notificationEndpoint service.
NotificationEndpointService is an http client for the influxdb.NotificationEndpointService server implementation.
NotificationRuleBackend is all services and associated parameters required to construct the NotificationRuleBackendHandler.
NotificationRuleHandler is the handler for the notification rule service.
NotificationRuleService is an http client that implements the NotificationRuleStore interface.
PlatformHandler is a collection of all the service handlers.
QueryAnalysis is a structured response of errors.
QueryDialect is the formatting options for the query response.
QueryRequest is a flux query request.
RestoreBackend is all services and associated parameters required to construct the RestoreHandler.
RestoreHandler is http handler for restore service.
ScraperBackend is all services and associated parameters required to construct the ScraperHandler.
ScraperHandler represents an HTTP API handler for scraper targets.
ScraperService connects to Influx via HTTP using tokens to manage scraper targets.
Service connects to an InfluxDB via HTTP.
SourceBackend is all services and associated parameters required to construct the SourceHandler.
SourceHandler is a handler for sources.
SourceService connects to Influx via HTTP using tokens to manage sources.
SpanTransport injects the http.RoundTripper.RoundTrip() request with a span.
SpecificURMSvc is a URM client that speaks to a specific resource with a specified user type.
Task is a package-specific Task format that preserves the expected format for the API, where time values are represented as strings.
TaskBackend is all services and associated parameters required to construct the TaskHandler.
TaskHandler represents an HTTP API handler for tasks.
TaskService connects to Influx via HTTP using tokens to manage tasks.
TelegrafBackend is all services and associated parameters required to construct the TelegrafHandler.
TelegrafHandler is the handler for the telegraf service.
TelegrafService is an http client that speaks to the telegraf service via HTTP.
UserResourceMappingService is the struct of urm service.
VariableBackend is all services and associated parameters required to construct the VariableHandler.
VariableHandler is the handler for the variable service.
VariableService is a variable service over HTTP to the influxdb server.
WriteBackend is all services and associated parameters required to construct the WriteHandler.
WriteHandler receives line protocol and sends to a publish function.
WriteService sends data over HTTP to influxdb via line protocol.

# Interfaces

AuthzError is returned for authorization errors.
DocumentService is an interface HTTP-exposed portion of the document service.
FeatureProxyHandler is an HTTP proxy that conditionally forwards requests to another backend.
Flusher flushes data from a store to reset; used for testing.
HTTPDialect is an encoding dialect that can write metadata to HTTP headers.

# Type aliases

APIHandlerOptFn is a functional input param to set parameters on the APIHandler.
WriteHandlerOption is a functional option for a *WriteHandler.