xw

package module
v0.0.0-...-bc4f0fb Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2023 License: MIT Imports: 40 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ErrInternalServer = "E_INTERNAL_SERVER"
	ErrBadRequest     = "E_BAD_REQ"
	ErrNotFound       = "E_NOT_FOUND"
)

Error constants

View Source
const (
	TokenHeader     = "Authorization"
	TokenCookie     = "accessToken"
	RefreshTokenKey = "refreshToken"
	ExpiresInKey    = "expiresIn"
)

Various constants

Variables

This section is empty.

Functions

func Authenticate

func Authenticate(c Context) error

Authenticate ...

func Body

func Body[T any](c Context) (*T, error)

Body ...

func BodyP

func BodyP[T any](c Context) *T

BodyP ...

func CreateChiMiddleware

func CreateChiMiddleware(fn MiddlewareHandler, mwCtx Context) func(http.Handler) http.Handler

CreateChiMiddleware ...

func CreateLogger

func CreateLogger(level ...zerolog.Level)

CreateLogger ...

func SetDefaultMiddleware

func SetDefaultMiddleware(r *chi.Mux, opts *Options) error

SetDefaultMiddleware ...

func SetMetricsMiddleware

func SetMetricsMiddleware(r *chi.Mux, opts *Options) error

SetMetricsMiddleware enables Prometheus endpoint

func SetMiddleware

func SetMiddleware(r *chi.Mux, middleware ...func(http.Handler) http.Handler) error

SetMiddleware enables setting additional middleware

func SetRequestLogger

func SetRequestLogger(r *chi.Mux, opts *Options) error

SetRequestLogger enables request logging

func SetTracingMiddleware

func SetTracingMiddleware(r *chi.Mux, opts *Options) error

SetTracingMiddleware enables OTEL tracing

Types

type AuthConfiguration

type AuthConfiguration func(auth *AuthOptions) error

AuthConfiguration ...

func WithAPIKey

func WithAPIKey() AuthConfiguration

WithAPIKey ...

func WithAuthClient

func WithAuthClient(clientID string, secret ...string) AuthConfiguration

WithAuthClient sets oidc client and secret if present

func WithCookieAuth

func WithCookieAuth() AuthConfiguration

WithCookieAuth enables reading auth data from cookies

func WithOIDC

func WithOIDC(cfg *AuthServerOptions) AuthConfiguration

WithOIDC ...

type AuthOptions

type AuthOptions struct {
	AuthServerOptions *AuthServerOptions

	ClientID string
	Secret   string

	AuthCookie       bool
	SecureAuthCookie bool
	APIKeyAuth       bool
}

AuthOptions ...

type AuthServerOptions

type AuthServerOptions struct {
	ServerURL         string
	WellKnownURL      string
	TokenURI          string
	AuthURI           string
	RefreshURI        string
	Realm             string
	RedirectURL       string
	ClientRedirectURL string
}

AuthServerOptions ...

type Claims

type Claims struct {
	AuthTime       int      `json:"auth_time"`
	Jti            string   `json:"jti"`
	Iss            string   `json:"iss"`
	Sub            string   `json:"sub"`
	Typ            string   `json:"typ"`
	Azp            string   `json:"azp"`
	SessionState   string   `json:"session_state"`
	Acr            string   `json:"acr"`
	AllowedOrigins []string `json:"allowed-origins"`
	RealmAccess    struct {
		Roles []string `json:"roles"`
	} `json:"realm_access"`
	ResourceAccess struct {
		Account struct {
			Roles []string `json:"roles"`
		} `json:"account"`
	} `json:"resource_access"`
	Scope             string `json:"scope"`
	Sid               string `json:"sid"`
	EmailVerified     bool   `json:"email_verified"`
	Name              string `json:"name"`
	PreferredUsername string `json:"preferred_username"`
	GivenName         string `json:"given_name"`
	FamilyName        string `json:"family_name"`
	Email             string `json:"email"`
}

Claims ...

type Context

type Context interface {
	// Param returns all path params
	Param(id string) string

	// Query returns all query params
	Query(id string) string

	// Headers returns all headers
	Headers() Params

	// Body returns the request body
	Body() any

	// BindBody binds the body value to a struct
	BindBody(to any) error

	// BindBodyP binds the body or panics
	BindBodyP(to any) any

	// Raw handles http.Handler requests
	Raw(http.Handler) error

	// JSON returns JSON reply
	JSON(body any, statusCode ...int) error

	// Error returns Error reply
	Error(body any, statusCode ...int) error

	// Status sends an empty reply with specified status code
	Status(statusCode int) error

	// ResponseBody ...
	ResponseBody() any

	// StatusCode ...
	StatusCode() int

	// RequestError ...
	RequestError() any

	Request() *http.Request

	JWKS() jwk.Set

	SetJWKS(k jwk.Set)

	SetClaims(claims *Claims)

	Claims() *Claims

	Context() context.Context

	// HTTPHandler returns registered handler
	HTTPHandler() http.Handler
}

Context ...

type Error

type Error struct {
	ID             int         `json:"id,omitempty" yaml:"id,omitempty"`
	Code           string      `json:"code,omitempty" yaml:"code,omitempty"`
	Msg            string      `json:"message,omitempty" yaml:"message,omitempty"`
	AdditionalData *JSONObject `json:"data,omitempty" yaml:"data,omitempty"`
	Errors         []any       `json:"errors,omitempty" yaml:"errors,omitempty"`
}

Error ...

func Err

func Err(code string) *Error

Err is the constructor for Error

func (*Error) Data

func (e *Error) Data(data *JSONObject) *Error

Data sets the dao property for Error

func (*Error) Errs

func (e *Error) Errs(data []any) *Error

Errs returns xw.Error with provided errors

func (*Error) Marshal

func (e *Error) Marshal() ([]byte, error)

Marshal ...

func (*Error) MarshalP

func (e *Error) MarshalP() []byte

MarshalP ...

func (*Error) Message

func (e *Error) Message(msg string) *Error

Message sets the message for Error

func (*Error) SetID

func (e *Error) SetID(id int) *Error

SetID sets the error ID

func (*Error) Unmarshal

func (e *Error) Unmarshal(b []byte) error

Unmarshal ...

type Group

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

Group ...

func NewGroup

func NewGroup(path string, routes ...*Route) *Group

NewGroup ...

func (*Group) Auth

func (g *Group) Auth() *Group

Auth sets auth flag

func (*Group) KeyAuth

func (g *Group) KeyAuth() *Group

KeyAuth sets key auth flag

func (*Group) Middleware

func (g *Group) Middleware(fns ...MiddlewareHandler) *Group

Middleware ...

func (*Group) Role

func (g *Group) Role(role ...string) *Group

Role sets roles to verify

func (*Group) Tag

func (g *Group) Tag(tags ...string) *Group

Tag sets tag(s) for the group

type Handler

type Handler func(c Context) error

Handler ...

type JSONObject

type JSONObject map[string]interface{}

JSONObject ...

type MiddlewareHandler

type MiddlewareHandler func(c Context) error

MiddlewareHandler ...

type OpenAPIOptions

type OpenAPIOptions struct {
	OASVersion string
	Servers    []string

	Title       string
	Description string
	Version     string

	StripPrefixes []string

	Swagger bool
	Rapidoc bool
}

OpenAPIOptions for initing openapi3.Reflector

type Options

type Options struct {
	Server *ServerOptions

	AuthOptions      *AuthOptions
	TelemetryOptions *TelemetryOptions

	OAS *OpenAPIOptions
}

Options ...

type ParamLocation

type ParamLocation string

ParamLocation is a type for parameter location (header, path, query)

const (
	ParamLocationHeader ParamLocation = "header"
	ParamLocationPath   ParamLocation = "path"
	ParamLocationQuery  ParamLocation = "query"
)

Possible values for ParamLocation

type Parameter

type Parameter struct {
	Title    string
	Type     string
	Location ParamLocation
}

Parameter definition

type Params

type Params map[string]string

Params ...

func (Params) Get

func (p Params) Get(id string) string

Get one

type Response

type Response struct {
	Code int
	Body any
}

Response defines a single response dao (code + entity)

type Route

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

Route ...

func Delete

func Delete[T any](path string, fn Handler) *Route

Delete method

func Get

func Get[T any](path string, fn Handler) *Route

Get method

func NewRoute

func NewRoute(path, method string, spec *Spec, fn Handler) *Route

NewRoute ...

func Patch

func Patch[B any, T any](path string, fn Handler) *Route

Patch method

func Post

func Post[B any, T any](path string, fn Handler) *Route

Post method

func Put

func Put[B any, T any](path string, fn Handler) *Route

Put method

func (*Route) Auth

func (r *Route) Auth() *Route

Auth sets auth flag

func (*Route) Desc

func (r *Route) Desc(desc string) *Route

Desc sets the spec description

func (*Route) KeyAuth

func (r *Route) KeyAuth() *Route

KeyAuth sets key auth flag

func (*Route) Middleware

func (r *Route) Middleware(middleware ...MiddlewareHandler) *Route

Middleware ...

func (*Route) Query

func (r *Route) Query(params any) *Route

Query sets query params

func (*Route) Role

func (r *Route) Role(role ...string) *Route

Role sets roles

func (*Route) Spec

func (r *Route) Spec() *Spec

Spec allows access to Spec of the route

func (*Route) Tag

func (r *Route) Tag(tags ...string) *Route

Tag adds tag(s) to route

func (*Route) Title

func (r *Route) Title(title string) *Route

Title sets the spec Summary

func (*Route) With

func (r *Route) With(opts ...SpecOpt) *Route

With spec option

type Server

type Server interface {
	Route(route ...*Route) Server
	Group(path string, routes ...*Route) *Group
	Groups(groups ...*Group) Server
	Get(path string, handlerFn http.HandlerFunc) Server
	Post(path string, handlerFn http.HandlerFunc) Server
	Put(path string, handlerFn http.HandlerFunc) Server
	Patch(path string, handlerFn http.HandlerFunc) Server
	Delete(path string, handlerFn http.HandlerFunc) Server
	Listen() error
}

Server ...

func Default

func Default(id string, port int, additional ...ServerConfiguration) Server

Default creates a server with _sensible_ defaults

func From

func From(configFile string) Server

From creates a server by loading a config file

func New

func New(cfgs ...ServerConfiguration) Server

New ...

type ServerConfiguration

type ServerConfiguration func(s *server) error

ServerConfiguration ...

func WithAuth

func WithAuth(cfgs ...AuthConfiguration) ServerConfiguration

WithAuth configures OpenID connect

func WithDefaultMiddleware

func WithDefaultMiddleware() ServerConfiguration

WithDefaultMiddleware enables default middleware

func WithFrontend

func WithFrontend(fe any) ServerConfiguration

WithFrontend enables serving frontend

func WithID

func WithID(id string) ServerConfiguration

WithID sets the ID of the server

func WithMetrics

func WithMetrics(uri ...string) ServerConfiguration

WithMetrics enables Prometheus metrics

func WithMiddleware

func WithMiddleware(middleware ...func(http.Handler) http.Handler) ServerConfiguration

WithMiddleware enables additional middleware

func WithOpenAPI

func WithOpenAPI(title, desc, version string) ServerConfiguration

WithOpenAPI enables OAS and sets title, description and version

func WithPort

func WithPort(port int) ServerConfiguration

WithPort sets server port

func WithRapiDoc

func WithRapiDoc() ServerConfiguration

WithRapiDoc enables RapiDoc UI

func WithReflector

func WithReflector(ref *openapi3.Reflector) ServerConfiguration

WithReflector sets a custom openapi3.Reflector

func WithRequestLogging

func WithRequestLogging() ServerConfiguration

WithRequestLogging enables request logger

func WithRouter

func WithRouter(r *chi.Mux) ServerConfiguration

WithRouter sets the Chi router

func WithStripPrefixes

func WithStripPrefixes(prefixes ...string) ServerConfiguration

WithStripPrefixes sets which prefixes should be stripped from components in OAS

func WithSwagger

func WithSwagger() ServerConfiguration

WithSwagger enables Swagger UI

func WithTracing

func WithTracing(url ...string) ServerConfiguration

WithTracing enables tracing

type ServerOptions

type ServerOptions struct {
	ID   string
	Port int

	RequestLogging bool

	FrontendPath string
	FrontendFS   *embed.FS
}

ServerOptions ...

type Spec

type Spec struct {
	Path         string
	OriginalPath string
	PathPrefix   string
	Method       string
	Body         interface{}
	Responses    []*Response
	Parameters   []*Parameter
	Tags         []string
	Summary      string
	Description  string
	Op           *openapi3.Operation
	Auth         bool
	Validate     bool
	AuthAPI      bool
}

Spec holds dao for creating an OpenAPI spec for a route

func DeleteOp

func DeleteOp(routePath string, res any, opts ...SpecOpt) *Spec

DeleteOp constructs a GET operation

func GetOp

func GetOp(routePath string, res any, opts ...SpecOpt) *Spec

GetOp constructs a GET operation

func Of

func Of(opts ...SpecOpt) *Spec

Of constructs a new Spec

func PatchOp

func PatchOp(routePath string, body any, res any, opts ...SpecOpt) *Spec

PatchOp constructs a PATCH operation

func PostOp

func PostOp(routePath string, body any, res any, opts ...SpecOpt) *Spec

PostOp constructs a POST operation

func PutOp

func PutOp(routePath string, body any, res any, opts ...SpecOpt) *Spec

PutOp constructs a PUT operation

func (*Spec) Build

func (s *Spec) Build(ref *openapi3.Reflector) error

Build builds an openapi3.Spec

func (*Spec) FullPath

func (s *Spec) FullPath() string

FullPath returns url with prefix if present

func (*Spec) FullRouterPath

func (s *Spec) FullRouterPath() string

FullRouterPath returns url with prefix if present

func (*Spec) With

func (s *Spec) With(opts ...SpecOpt) *Spec

With is a generic method to add/replace opts after Spec is already created

func (*Spec) WithAPIAuth

func (s *Spec) WithAPIAuth() *Spec

WithAPIAuth set api auth for spec

func (*Spec) WithAuth

func (s *Spec) WithAuth() *Spec

WithAuth set auth for spec

func (*Spec) WithQueryObject

func (s *Spec) WithQueryObject(obj any) *Spec

WithQueryObject ...

func (*Spec) WithTags

func (s *Spec) WithTags(tags ...string) *Spec

WithTags ...

func (*Spec) WithValidation

func (s *Spec) WithValidation() *Spec

WithValidation ...

type SpecOpt

type SpecOpt func(s *Spec) error

SpecOpt ...

func WithBody

func WithBody(body any) SpecOpt

WithBody adds a body for the operation

func WithDescription

func WithDescription(description string) SpecOpt

WithDescription adss a description

func WithErrBadRequest

func WithErrBadRequest(message ...string) SpecOpt

WithErrBadRequest creates a bad request error response Opt

func WithErrNotFound

func WithErrNotFound(message ...string) SpecOpt

WithErrNotFound creates a not found error response Opt

func WithError

func WithError(errorCode int, message ...string) SpecOpt

WithError creates an error response Opt

func WithForbidden

func WithForbidden(message ...string) SpecOpt

WithForbidden creates a forbidden error response Opt

func WithInternalError

func WithInternalError(message ...string) SpecOpt

WithInternalError creates an internal server error response Opt

func WithMethod

func WithMethod(m string) SpecOpt

WithMethod adds a method for the opration

func WithOriginalPath

func WithOriginalPath(p string) SpecOpt

WithOriginalPath adds a path to the request

func WithParam

func WithParam(loc ParamLocation, title string, paramType ...string) SpecOpt

WithParam appends a path parameter

func WithParams

func WithParams(params []*Parameter) SpecOpt

WithParams merges params to operation

func WithPath

func WithPath(p string) SpecOpt

WithPath adds a path to the request

func WithPathPrefix

func WithPathPrefix(p string) SpecOpt

WithPathPrefix adds a prefix for the request

func WithResponse

func WithResponse(body any, code ...int) SpecOpt

WithResponse appends a response

func WithSummary

func WithSummary(summary string) SpecOpt

WithSummary adds a summary

func WithTags

func WithTags(tags ...string) SpecOpt

WithTags appends tags to the operation

func WithUnauthorized

func WithUnauthorized(message ...string) SpecOpt

WithUnauthorized creates an unauthorized error response Opt

type TelemetryOptions

type TelemetryOptions struct {
	OpenTelemetryURL string
	MetricsURI       string
}

TelemetryOptions ...

type WellKnown

type WellKnown struct {
	Issuer                                                    string   `json:"issuer"`
	AuthorizationEndpoint                                     string   `json:"authorization_endpoint"`
	TokenEndpoint                                             string   `json:"token_endpoint"`
	IntrospectionEndpoint                                     string   `json:"introspection_endpoint"`
	UserinfoEndpoint                                          string   `json:"userinfo_endpoint"`
	EndSessionEndpoint                                        string   `json:"end_session_endpoint"`
	FrontchannelLogoutSessionSupported                        bool     `json:"frontchannel_logout_session_supported"`
	FrontchannelLogoutSupported                               bool     `json:"frontchannel_logout_supported"`
	JwksURI                                                   string   `json:"jwks_uri"`
	CheckSessionIframe                                        string   `json:"check_session_iframe"`
	GrantTypesSupported                                       []string `json:"grant_types_supported"`
	AcrValuesSupported                                        []string `json:"acr_values_supported"`
	ResponseTypesSupported                                    []string `json:"response_types_supported"`
	SubjectTypesSupported                                     []string `json:"subject_types_supported"`
	IDTokenSigningAlgValuesSupported                          []string `json:"id_token_signing_alg_values_supported"`
	IDTokenEncryptionAlgValuesSupported                       []string `json:"id_token_encryption_alg_values_supported"`
	IDTokenEncryptionEncValuesSupported                       []string `json:"id_token_encryption_enc_values_supported"`
	UserinfoSigningAlgValuesSupported                         []string `json:"userinfo_signing_alg_values_supported"`
	UserinfoEncryptionAlgValuesSupported                      []string `json:"userinfo_encryption_alg_values_supported"`
	UserinfoEncryptionEncValuesSupported                      []string `json:"userinfo_encryption_enc_values_supported"`
	RequestObjectSigningAlgValuesSupported                    []string `json:"request_object_signing_alg_values_supported"`
	RequestObjectEncryptionAlgValuesSupported                 []string `json:"request_object_encryption_alg_values_supported"`
	RequestObjectEncryptionEncValuesSupported                 []string `json:"request_object_encryption_enc_values_supported"`
	ResponseModesSupported                                    []string `json:"response_modes_supported"`
	RegistrationEndpoint                                      string   `json:"registration_endpoint"`
	TokenEndpointAuthMethodsSupported                         []string `json:"token_endpoint_auth_methods_supported"`
	TokenEndpointAuthSigningAlgValuesSupported                []string `json:"token_endpoint_auth_signing_alg_values_supported"`
	IntrospectionEndpointAuthMethodsSupported                 []string `json:"introspection_endpoint_auth_methods_supported"`
	IntrospectionEndpointAuthSigningAlgValuesSupported        []string `json:"introspection_endpoint_auth_signing_alg_values_supported"`
	AuthorizationSigningAlgValuesSupported                    []string `json:"authorization_signing_alg_values_supported"`
	AuthorizationEncryptionAlgValuesSupported                 []string `json:"authorization_encryption_alg_values_supported"`
	AuthorizationEncryptionEncValuesSupported                 []string `json:"authorization_encryption_enc_values_supported"`
	ClaimsSupported                                           []string `json:"claims_supported"`
	ClaimTypesSupported                                       []string `json:"claim_types_supported"`
	ClaimsParameterSupported                                  bool     `json:"claims_parameter_supported"`
	ScopesSupported                                           []string `json:"scopes_supported"`
	RequestParameterSupported                                 bool     `json:"request_parameter_supported"`
	RequestURIParameterSupported                              bool     `json:"request_uri_parameter_supported"`
	RequireRequestURIRegistration                             bool     `json:"require_request_uri_registration"`
	CodeChallengeMethodsSupported                             []string `json:"code_challenge_methods_supported"`
	TLSClientCertificateBoundAccessTokens                     bool     `json:"tls_client_certificate_bound_access_tokens"`
	RevocationEndpoint                                        string   `json:"revocation_endpoint"`
	RevocationEndpointAuthMethodsSupported                    []string `json:"revocation_endpoint_auth_methods_supported"`
	RevocationEndpointAuthSigningAlgValuesSupported           []string `json:"revocation_endpoint_auth_signing_alg_values_supported"`
	BackchannelLogoutSupported                                bool     `json:"backchannel_logout_supported"`
	BackchannelLogoutSessionSupported                         bool     `json:"backchannel_logout_session_supported"`
	DeviceAuthorizationEndpoint                               string   `json:"device_authorization_endpoint"`
	BackchannelTokenDeliveryModesSupported                    []string `json:"backchannel_token_delivery_modes_supported"`
	BackchannelAuthenticationEndpoint                         string   `json:"backchannel_authentication_endpoint"`
	BackchannelAuthenticationRequestSigningAlgValuesSupported []string `json:"backchannel_authentication_request_signing_alg_values_supported"`
	RequirePushedAuthorizationRequests                        bool     `json:"require_pushed_authorization_requests"`
	PushedAuthorizationRequestEndpoint                        string   `json:"pushed_authorization_request_endpoint"`
	MtlsEndpointAliases                                       struct {
		TokenEndpoint                      string `json:"token_endpoint"`
		RevocationEndpoint                 string `json:"revocation_endpoint"`
		IntrospectionEndpoint              string `json:"introspection_endpoint"`
		DeviceAuthorizationEndpoint        string `json:"device_authorization_endpoint"`
		RegistrationEndpoint               string `json:"registration_endpoint"`
		UserinfoEndpoint                   string `json:"userinfo_endpoint"`
		PushedAuthorizationRequestEndpoint string `json:"pushed_authorization_request_endpoint"`
		BackchannelAuthenticationEndpoint  string `json:"backchannel_authentication_endpoint"`
	} `json:"mtls_endpoint_aliases"`
}

WellKnown ...

Directories

Path Synopsis
cmd
xw

Jump to

Keyboard shortcuts

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