Documentation ¶
Index ¶
- Variables
- func AddRequestDetailsToCtx(ctx context.Context, details RequestDetails) context.Context
- func ConfigureAndStartHttpServer(lc fx.Lifecycle, config Configuration, logger *zap.SugaredLogger, ...) error
- func ExtractPathParamsFromRequestContext[T any](ctx context.Context) (*T, serr.Error)
- func ExtractPrincipalFromContext(ctx context.Context) (*iam.ArmoryCloudPrincipal, serr.Error)
- func ExtractQueryParamsFromRequestContext[T any](ctx context.Context) (*T, serr.Error)
- func LogAPIError(request *http.Request, errorID string, apiErr serr.Error, statusCode int, ...)
- type AuthService
- type AuthZValidatorFn
- type Configuration
- type Controller
- type Handler
- type HandlerConfig
- type IController
- type IControllerAuthZValidator
- type IControllerPrefix
- type ManagementController
- type RequestDetails
- type RequestLoggingConfiguration
- type Response
- type SPAConfiguration
- type Void
Constants ¶
This section is empty.
Variables ¶
var Module = fx.Options( 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.Metrics, serverControllers controllers, managementControllers managementControllers, as AuthService, md metadata.ApplicationMetadata, is *info.InfoService, ) error
func ExtractPathParamsFromRequestContext ¶ added in v1.16.0
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
ExtractPrincipalFromContext retrieves the principal from the context and returns a serr.Error
func ExtractQueryParamsFromRequestContext ¶ added in v1.16.0
ExtractQueryParamsFromRequestContext accepts a type param T and attempts to map the HTTP request's query params into T.
func LogAPIError ¶
Types ¶
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 Configuration ¶
type Configuration struct { RequestLogging RequestLoggingConfiguration SPA SPAConfiguration HTTP http.HTTP Management http.HTTP }
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
func NewHandler ¶
func NewHandler[REQUEST, RESPONSE any](f func(ctx context.Context, request REQUEST) (*Response[RESPONSE], serr.Error), config HandlerConfig) Handler
NewHandler creates a Handler from a handler function and server.HandlerConfig
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, this will cause the principal to be nil in the request context AuthOptOut bool // AuthZValidator see AuthZValidatorFn AuthZValidator AuthZValidatorFn }
HandlerConfig config that configures a handler AKA an endpoint
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 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 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 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 }
RequestDetails use server.ExtractRequestDetailsFromContext to get this out of the request context
func ExtractRequestDetailsFromContext ¶ added in v1.16.2
func ExtractRequestDetailsFromContext(ctx context.Context) (*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 ¶
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 ¶
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
type SPAConfiguration ¶ added in v1.18.0
Source Files ¶
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 |