server

package
v1.45.2 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2023 License: Apache-2.0 Imports: 41 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrDuplicateHandlerRegistered = errors.New("there was a duplicate handler registered")
View Source
var (
	HandlerByLabel = func(label string) HandlerSelector {
		return func(handler Handler) bool {
			return handler.Config().Label == label
		}
	}
)
View Source
var Module = fx.Options(
	fx.Provide(validator.New),
	fx.Invoke(ConfigureAndStartHttpServer),
)

Functions

func AddRequestDetailsToCtx added in v1.15.3

func AddRequestDetailsToCtx(ctx context.Context, details RequestDetails) context.Context

AddRequestDetailsToCtx is exposed for testing and allows tests to configure the request details when testing handler functions

func ConfigureAndStartHttpServer

func ConfigureAndStartHttpServer(
	lc fx.Lifecycle,
	config Configuration,
	logger *zap.SugaredLogger,
	ms metrics.MetricsSvc,
	serverControllers controllers,
	managementControllers managementControllers,
	as AuthService,
	md metadata.ApplicationMetadata,
	requestValidator *validator.Validate,
	is *info.InfoService,
) error

func Example_Handler added in v1.28.0

func Example_Handler()

func Example_New1ArgHandler added in v1.28.0

func Example_New1ArgHandler()

func Example_New3ArgHandler added in v1.28.0

func Example_New3ArgHandler()

func ExtractHeaderParamsFromRequestContext added in v1.28.0

func ExtractHeaderParamsFromRequestContext[T any](ctx context.Context) (*T, serr.Error)

ExtractHeaderParamsFromRequestContext accepts a type param T and attempts to map the HTTP header's param into T. Use `mapstructure:"<your header name>"` to annotate field to match the header. Headers can be a string array, so make sure your field is array type as well.

func ExtractLoggingFields added in v1.29.0

func ExtractLoggingFields(metadata map[string]string) []any

func ExtractPathParamsFromRequestContext added in v1.16.0

func ExtractPathParamsFromRequestContext[T any](ctx context.Context) (*T, serr.Error)

ExtractPathParamsFromRequestContext accepts a type param T and attempts to map the HTTP request's path params into T.

func ExtractPrincipalFromContext added in v1.16.0

func ExtractPrincipalFromContext(ctx context.Context) (*iam.ArmoryCloudPrincipal, serr.Error)

ExtractPrincipalFromContext retrieves the principal from the context and returns a serr.Error

func ExtractQueryParamsFromRequestContext added in v1.16.0

func ExtractQueryParamsFromRequestContext[T any](ctx context.Context) (*T, serr.Error)

ExtractQueryParamsFromRequestContext accepts a type param T and attempts to map the HTTP request's query params into T. Query parameters can be a string array, so make sure your target field definition is array type as well.

func ExtractResponseDataAndCode added in v1.28.0

func ExtractResponseDataAndCode[TYPE any](t *testing.T, r *httptest.ResponseRecorder) (*TYPE, int)

func LogAPIError

func LogAPIError(
	request *http.Request,
	errorID string,
	apiErr serr.Error,
	statusCode int,
	log *zap.SugaredLogger,
)

Types

type ArgumentDataSource added in v1.28.0

type ArgumentDataSource int
const (
	PathContextSource   ArgumentDataSource = 0
	QueryContextSource  ArgumentDataSource = 1
	HeaderContextSource ArgumentDataSource = 2
)

type ArmoryPrincipalArgument added in v1.28.0

type ArmoryPrincipalArgument struct {
	*iam.ArmoryCloudPrincipal
}

func (ArmoryPrincipalArgument) Source added in v1.28.0

func (ArmoryPrincipalArgument) Source() ArgumentDataSource

type AuthService added in v1.17.1

type AuthService interface {
	VerifyPrincipalAndSetContext(tokenOrRawHeader string, c *gin.Context) error
}

func NewNoopAuthService added in v1.17.1

func NewNoopAuthService() AuthService

type AuthZValidatorFn

type AuthZValidatorFn func(p *iam.ArmoryCloudPrincipal) (string, bool)

AuthZValidatorFn a function that takes the authenticated principal and returns whether the principal is authorized. return true if the user is authorized return false if the user is NOT authorized and a string indicated the reason.

type AuthZValidatorV2Fn added in v1.28.0

type AuthZValidatorV2Fn func(ctx context.Context, p *iam.ArmoryCloudPrincipal) (string, bool)

AuthZValidatorV2Fn a function that takes the authenticated principal and passes current context, so you can make auth decision based on the additional conditions (i.e. headers, path parameters, etc. ) return true if the user is authorized return false if the user is NOT authorized

type Configuration

type Configuration struct {
	RequestLogging RequestLoggingConfiguration
	SPA            SPAConfiguration
	HTTP           http.HTTP
	Management     http.HTTP
	Profile        ProfileConfiguration
}

type Controller

type Controller struct {
	fx.Out
	Controller IController `group:"server"`
}

Controller the expected way of defining endpoint collections for an Armory application See the bellow example and IController, IControllerPrefix, IControllerAuthZValidator for options

EX:

package controllers

import (
	"context"
	"github.com/armory-io/go-commons/server"
	"github.com/armory-io/sccp/internal/sccp/k8s"
	"go.uber.org/zap"
	"net/http"
)

type ClusterController struct {
	log *zap.SugaredLogger
	k8s *k8s.Service
}

func NewClusterController(
	log *zap.SugaredLogger,
	k8sService *k8s.Service,
) server.Controller {
	return server.Controller{
		Controller: &ClusterController{
			log: log,
			k8s: k8sService,
		},
	}
}

func (c *ClusterController) Prefix() string {
	return "/clusters"
}

func (c *ClusterController) Handlers() []server.Handler {
	return []server.Handler{
		server.NewHandler(c.createClusterHandler, server.HandlerConfig{
			Method: http.MethodPost,
		}),
	}
}

type (
	createClusterRequest struct {
		AgentIdentifier string `json:"agentIdentifier" validate:"required,min=3,max=255"`
		ClientId        string `json:"clientId" validate:"required"`
		ClientSecret    string `json:"clientSecret" validate:"required"`
	}
	createClusterResponse struct {
		ClusterId string `json:"clusterId"`
	}
)

func (c *ClusterController) createClusterHandler(
	_ context.Context,
	req createClusterRequest,
) (*server.Response[createClusterResponse], server.Response) {
	id, err := c.k8s.CreateCluster(req.AgentIdentifier, req.ClientId, req.ClientSecret)

	if err != nil {
		return nil, server.NewErrorResponseFromApiError(server.APIError{
			Message: "Failed to create sandbox cluster",
		}, server.WithCause(err))
	}

	return server.SimpleResponse(createClusterResponse{
		ClusterId: id,
	}), nil
}

type Handler

type Handler interface {
	GetGinHandlerFn(log *zap.SugaredLogger, v *validator.Validate, handler *handlerDTO) gin.HandlerFunc
	Config() HandlerConfig
}

Handler The handler interface Instances of this interface should only ever be created by NewHandler, which happens automatically during server initialization The expected way that handlers are created is by creating a provider that provides an instance of Controller

type Handler1Extensions added in v1.28.0

type Handler1Extensions[REQUEST, RESPONSE any] struct {
	// contains filtered or unexported fields
}

func NewHandler

func NewHandler[REQUEST, RESPONSE any](f func(ctx context.Context, request REQUEST) (*Response[RESPONSE], serr.Error), config HandlerConfig) *Handler1Extensions[REQUEST, RESPONSE]

NewHandler creates a Handler from a handler function and server.HandlerConfig

func (Handler1Extensions) Config added in v1.28.0

func (r Handler1Extensions) Config() HandlerConfig

func (Handler1Extensions) GetGinHandlerFn added in v1.28.0

func (r Handler1Extensions) GetGinHandlerFn(log *zap.SugaredLogger, requestValidator *validator.Validate, config *handlerDTO) gin.HandlerFunc

func (*Handler1Extensions[REQUEST, RESPONSE]) RegisterBeforeValidationHandler added in v1.28.0

func (r *Handler1Extensions[REQUEST, RESPONSE]) RegisterBeforeValidationHandler(beforeValidation func(body *REQUEST)) *Handler1Extensions[REQUEST, RESPONSE]

func (Handler1Extensions) RegisterResponseProcessor added in v1.28.0

func (r Handler1Extensions) RegisterResponseProcessor(processor ResponseProcessorFn) *handler[REQUEST, RESPONSE]

type Handler2Extensions added in v1.28.0

type Handler2Extensions[REQUEST, RESPONSE any, ARG HandlerArgument] struct {
	// contains filtered or unexported fields
}

func New1ArgHandler added in v1.28.0

func New1ArgHandler[REQUEST, RESPONSE any, CTX HandlerArgument](f func(ctx context.Context, request REQUEST, arg1 CTX) (*Response[RESPONSE], serr.Error), config HandlerConfig) *Handler2Extensions[REQUEST, RESPONSE, CTX]

func (Handler2Extensions) Config added in v1.28.0

func (r Handler2Extensions) Config() HandlerConfig

func (Handler2Extensions) GetGinHandlerFn added in v1.28.0

func (r Handler2Extensions) GetGinHandlerFn(log *zap.SugaredLogger, requestValidator *validator.Validate, config *handlerDTO) gin.HandlerFunc

func (*Handler2Extensions[REQUEST, RESPONSE, ARG]) RegisterBeforeValidationHandler added in v1.28.0

func (r *Handler2Extensions[REQUEST, RESPONSE, ARG]) RegisterBeforeValidationHandler(beforeValidation func(body *REQUEST, arg *ARG)) *Handler2Extensions[REQUEST, RESPONSE, ARG]

func (Handler2Extensions) RegisterResponseProcessor added in v1.28.0

func (r Handler2Extensions) RegisterResponseProcessor(processor ResponseProcessorFn) *handler[REQUEST, RESPONSE]

type Handler3Extensions added in v1.28.0

type Handler3Extensions[REQUEST, RESPONSE any, ARG1, ARG2 HandlerArgument] struct {
	// contains filtered or unexported fields
}

func New2ArgHandler added in v1.28.0

func New2ArgHandler[REQUEST, RESPONSE any, CTX1 HandlerArgument, CTX2 HandlerArgument](f func(ctx context.Context, request REQUEST, arg1 CTX1, arg2 CTX2) (*Response[RESPONSE], serr.Error), config HandlerConfig) *Handler3Extensions[REQUEST, RESPONSE, CTX1, CTX2]

func (Handler3Extensions) Config added in v1.28.0

func (r Handler3Extensions) Config() HandlerConfig

func (Handler3Extensions) GetGinHandlerFn added in v1.28.0

func (r Handler3Extensions) GetGinHandlerFn(log *zap.SugaredLogger, requestValidator *validator.Validate, config *handlerDTO) gin.HandlerFunc

func (*Handler3Extensions[REQUEST, RESPONSE, ARG1, ARG2]) RegisterBeforeValidationHandler added in v1.28.0

func (r *Handler3Extensions[REQUEST, RESPONSE, ARG1, ARG2]) RegisterBeforeValidationHandler(beforeValidation func(body *REQUEST, arg1 *ARG1, arg2 *ARG2)) *Handler3Extensions[REQUEST, RESPONSE, ARG1, ARG2]

func (Handler3Extensions) RegisterResponseProcessor added in v1.28.0

func (r Handler3Extensions) RegisterResponseProcessor(processor ResponseProcessorFn) *handler[REQUEST, RESPONSE]

type Handler4Extensions added in v1.28.0

type Handler4Extensions[REQUEST, RESPONSE any, ARG1, ARG2, ARG3 HandlerArgument] struct {
	// contains filtered or unexported fields
}

func New3ArgHandler added in v1.28.0

func New3ArgHandler[REQUEST, RESPONSE any, CTX1 HandlerArgument, CTX2 HandlerArgument, CTX3 HandlerArgument](
	f func(ctx context.Context, request REQUEST, arg1 CTX1, arg2 CTX2, arg3 CTX3) (*Response[RESPONSE], serr.Error), config HandlerConfig) *Handler4Extensions[REQUEST, RESPONSE, CTX1, CTX2, CTX3]

func (Handler4Extensions) Config added in v1.28.0

func (r Handler4Extensions) Config() HandlerConfig

func (Handler4Extensions) GetGinHandlerFn added in v1.28.0

func (r Handler4Extensions) GetGinHandlerFn(log *zap.SugaredLogger, requestValidator *validator.Validate, config *handlerDTO) gin.HandlerFunc

func (*Handler4Extensions[REQUEST, RESPONSE, ARG1, ARG2, ARG3]) RegisterBeforeValidationHandler added in v1.28.0

func (r *Handler4Extensions[REQUEST, RESPONSE, ARG1, ARG2, ARG3]) RegisterBeforeValidationHandler(beforeValidation func(body *REQUEST, arg1 *ARG1, arg2 *ARG2, arg3 *ARG3)) *Handler4Extensions[REQUEST, RESPONSE, ARG1, ARG2, ARG3]

func (Handler4Extensions) RegisterResponseProcessor added in v1.28.0

func (r Handler4Extensions) RegisterResponseProcessor(processor ResponseProcessorFn) *handler[REQUEST, RESPONSE]

type HandlerArgument added in v1.28.0

type HandlerArgument interface {
	Source() ArgumentDataSource
}

HandlerArgument represents an interface of the generic argument passed into your handler method. The argument represents a strongly typed struct with the data obtained from http's request path parameters, query parameters or headers. There is also utility implementation ArmoryPrincipalArgument which provides access to entity issuing current request. The argument's fields allow typical validation annotations - should they fail - 400 status code with details will be reported back.

type HandlerConfig

type HandlerConfig struct {
	// Path The path or sub-path if a root path is set on the controller that the handler will be served on
	Path string
	// Method The HTTP method that the handler will be served on
	Method string
	// Consumes The content-type that the handler consumes, defaults to application/json
	Consumes string
	// Produces The content-type that the handler produces/offers, defaults to application/json
	Produces string
	// Default denotes that the handler should be used when the request doesn't specify a preferred Media/MIME type via the Accept header
	// Please note that one and only one handler for a given path/method combo can be marked as default, else a runtime error will be produced.
	Default bool
	// StatusCode The default status code to return when the request is successful, can be overridden by the handler by setting Response.StatusCode in the handler
	StatusCode int
	// AuthOptOut Set this to true if the handler should skip AuthZ and AuthN.
	AuthOptOut bool
	// AuthZValidator see AuthZValidatorFn
	AuthZValidator AuthZValidatorFn
	// AuthZValidatorExtended see AuthZValidatorV2Fn
	AuthZValidatorExtended AuthZValidatorV2Fn
	// Label Optional label(name) of the handler
	Label string
	// contains filtered or unexported fields
}

HandlerConfig config that configures a handler AKA an endpoint

type HandlerExtensionPoints added in v1.28.0

type HandlerExtensionPoints struct {
	BeforeRequestValidate beforeRequestValidateFn
}

HandlerExtensionPoints handler flow extensibility points - register specific handlers to plug additional processing in the pipeline

type HandlerSelector added in v1.28.0

type HandlerSelector func(handler Handler) bool

type HandlerTestContext added in v1.28.0

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

func NewHandlerTestContext added in v1.28.0

func NewHandlerTestContext(t *testing.T, target IController, selector HandlerSelector) *HandlerTestContext

func (*HandlerTestContext) BuildHandler added in v1.28.0

func (*HandlerTestContext) WithBody added in v1.28.0

func (h *HandlerTestContext) WithBody(t *testing.T, body interface{}) *HandlerTestContext

func (*HandlerTestContext) WithHttpMethod added in v1.28.0

func (h *HandlerTestContext) WithHttpMethod(_ *testing.T, method string) *HandlerTestContext

func (*HandlerTestContext) WithJSONBody added in v1.28.0

func (h *HandlerTestContext) WithJSONBody(_ *testing.T, body string) *HandlerTestContext

func (*HandlerTestContext) WithLogger added in v1.28.0

func (h *HandlerTestContext) WithLogger(_ *testing.T, logger *zap.SugaredLogger) *HandlerTestContext

func (*HandlerTestContext) WithPathParameters added in v1.28.0

func (h *HandlerTestContext) WithPathParameters(t *testing.T, pairs ...string) *HandlerTestContext

func (*HandlerTestContext) WithPrincipal added in v1.28.0

func (h *HandlerTestContext) WithPrincipal(_ *testing.T, principal *iam.ArmoryCloudPrincipal) *HandlerTestContext

func (*HandlerTestContext) WithRawBody added in v1.28.0

func (h *HandlerTestContext) WithRawBody(t *testing.T, body any) *HandlerTestContext

func (*HandlerTestContext) WithRequestHeaders added in v1.28.0

func (h *HandlerTestContext) WithRequestHeaders(t *testing.T, pairs ...string) *HandlerTestContext

func (*HandlerTestContext) WithRequestUrl added in v1.28.0

func (h *HandlerTestContext) WithRequestUrl(t *testing.T, stubUrl string) *HandlerTestContext

func (*HandlerTestContext) WithValidator added in v1.28.0

func (h *HandlerTestContext) WithValidator(_ *testing.T, v *validator.Validate) *HandlerTestContext

type IController

type IController interface {
	Handlers() []Handler
}

IController baseController the base IController interface, all controllers must impl this via providing an instance of Controller or ManagementController

type IControllerAuthZValidator

type IControllerAuthZValidator interface {
	AuthZValidator(p *iam.ArmoryCloudPrincipal) (string, bool)
}

IControllerAuthZValidator an IController can implement this interface to apply a common AuthZ validator to all exported handlers

type IControllerAuthZValidatorV2 added in v1.28.0

type IControllerAuthZValidatorV2 interface {
	AuthZValidator(ctx context.Context, p *iam.ArmoryCloudPrincipal) (string, bool)
}

IControllerAuthZValidatorV2 an IController can implement this interface to apply a common AuthZ validator to all exported handlers

type IControllerPostResponseProcessor added in v1.28.0

type IControllerPostResponseProcessor interface {
	ResponseProcessors() []ResponseProcessorWithOrder
}

IControllerPostResponseProcessor the IController can implement this interface to provide reponse processor to all exported handlers

type IControllerPrefix

type IControllerPrefix interface {
	Prefix() string
}

IControllerPrefix an IController can implement this interface to have all of its handler func paths prefixed with a common path partial

type LoggingMetadata added in v1.29.0

type LoggingMetadata struct {
	Logger   *zap.SugaredLogger
	Metadata map[string]string
}

type ManagementController

type ManagementController struct {
	fx.Out
	Controller IController `group:"management"`
}

ManagementController the same as Controller but the controllers in this group can be optionally configured to run on a separate port than the server controllers

type ProfileConfiguration added in v1.38.0

type ProfileConfiguration struct {
	Enabled        bool
	OverridePrefix string
}

ProfileConfiguration defines options for turning on the golang runtime profiler and having it serve http traffic (for retrieving reports)

type RequestDetails

type RequestDetails struct {
	// Headers the headers sent along with the request
	Headers http.Header
	// QueryParameters the decoded well-formed query params from the request
	// always a non-nil map containing all the valid query parameters found
	QueryParameters map[string][]string
	// PathParameters The map of path parameters if specified in the request configuration
	// ex: path: if the path was defined as "/customer/:id" and the request was for "/customer/foo"
	// PathParameters["id"] would equal "foo"
	PathParameters map[string]string
	// RequestPath the string representing requested resources i.e. /api/v1/organizations/:orgID/...
	RequestPath string
	// LoggingMetadata
	LoggingMetadata LoggingMetadata
}

RequestDetails use server.ExtractRequestDetailsFromContext to get this out of the request context

func ExtractRequestDetailsFromContext added in v1.16.2

func ExtractRequestDetailsFromContext(ctx requestDetailsContext) (*RequestDetails, serr.Error)

ExtractRequestDetailsFromContext fetches the server.RequestDetails from the context

type RequestLoggingConfiguration

type RequestLoggingConfiguration struct {
	// Enabled if set to true a request logging middleware will be applied to all requests
	Enabled bool
	// BlockList configure a set of endpoints to skip request logging on, such as the health check endpoints
	BlockList []string
	// Disable2XX if enabled requests inside the 200-299 range will not be logged
	Disable2XX bool
	// Disable3XX if enabled requests inside the 300-399 range will not be logged
	Disable3XX bool
	// Disable4XX if enabled requests inside the 400-499 range will not be logged
	Disable4XX bool
	// Disable5XX if enabled requests inside the 500-599 range will not be logged
	Disable5XX bool
}

RequestLoggingConfiguration enable request logging, by default all requests are logged. See fields for options on filtering what is logged

type Response

type Response[T any] struct {
	StatusCode int
	Headers    map[string][]string
	Body       T
}

Response The response wrapper for a handler response to be return to the client of the request StatusCode If set then it takes precedence to the default status code for the handler. Headers Any values set here will be added to the response sent to the client, if Content-Type is set here then

it will override the value set in HandlerConfig.Produces

func SimpleResponse

func SimpleResponse[T any](body T) *Response[T]

SimpleResponse a convenience function for wrapping a body in a response struct with defaults Use this if you do not need to supply custom headers or override the handlers default status code

func SimpleResponseWithStatus added in v1.28.0

func SimpleResponseWithStatus[T any](body T, status int) *Response[T]

SimpleResponseWithStatus a convenience function for wrapping a body in a response struct with defaults Use this if you do not need to supply custom headers

type ResponseProcessorFn added in v1.28.0

type ResponseProcessorFn func(ctx context.Context, bytes []byte) ([]byte, serr.Error)

ResponseProcessorFn function, executed after the handler processing is complete. It provides user a chance to get raw response bytes and allow extra processing of the response before sending it back to the caller

type ResponseProcessorWithOrder added in v1.28.0

type ResponseProcessorWithOrder struct {
	Order     int
	Processor ResponseProcessorFn
}

ResponseProcessorWithOrder structure wrapping response processors - if one wants to chain multiple processors, provide proper order to build the correct pipeline

type SPAConfiguration added in v1.18.0

type SPAConfiguration struct {
	Enabled   bool
	Prefix    string
	Directory string
}

type Void

type Void struct{}

Void an empty struct that can be used as a placeholder for requests/responses that do not have a body

Directories

Path Synopsis
Package serr This package contains all the logic and helper methods for creating and serializing API Errors This is in a separate package than server so that as a developer you get better intellisense when creating errors Heavily inspired from Nike Backstopper
Package serr This package contains all the logic and helper methods for creating and serializing API Errors This is in a separate package than server so that as a developer you get better intellisense when creating errors Heavily inspired from Nike Backstopper

Jump to

Keyboard shortcuts

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