rez

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Apr 9, 2024 License: GPL-3.0 Imports: 18 Imported by: 0

README

rez

REST (easy) framework in Go with out of the box OpenAPI generation, validation, dependency injection, and much more.

  • Dependency Injection How values are sent to middleware and endpoint functions.
  • Router Defining the routes, middlware, & documentation.
  • Middleware Code that runs before it reaches the final endpoint
  • Inspection How types are converted into documentation.
  • Validation How to control validation.
  • Documentation All the ways to specify documentation.
  • Site The main site type and its useful methods.
Example
type Echo struct {
	Message string `json:"message" api:"desc=A message to echo."`
}
site := rez.New(chi.NewRouter())
// /echo?message=HelloWorld!
site.Get("/echo", func(q rez.Query[Echo]) (*Echo, *rez.NotFound[string]) {
  if q.Value.Message == "" {
    return nil, rez.NewNotFound("message is required")
  }
  return &q.Value, nil
})
site.ServeSwaggerUI("/doc/swagger", nil)
site.ServeRedoc("/doc/redoc")
site.Listen(":3000")

More can be found in examples.

Dependency Injection

Dependency injection is used to pass arguments to a middleware or route functions. rez uses deps for dependency injection. There are several types that get injected out of the box:

  • context.Context: The context of the request.
  • deps.Scope: The scope which holds all the given values that can be injected for the current request. The root Site type has a parent scope which request scopes can inherit values from.
  • http.ResponseWriter: The outgoing response.
  • http.Request: The incoming request.
  • rez.Router: The reference to the router where the middleware was used or the route was defined on.
  • rez.Path[P]: A generic wrapper which holds the struct that is parsed from the path parameters. If the path is /task/{taskID} and the struct is type TaskPath struct { TaskID int } the TaskID property will be populated from the value in the URL.
  • rez.Query[Q]: A generic wrapper which holds the struct that is parsed from the query string. If the url is ?message=Hi&times=4 and the struct is type MyQuery struct { Message string, Times int } the Message and Times fields will be populated from the query string.
  • rez.Header[H]: A generic wrapper which holds the struct that is parsed from the headers.
  • rez.Body[B]: A generic wrapper which holds the type that is parsed from the request body.
  • rez.Request[B, P, Q]: A generic wrapper which holds the body, params, and query structs that are to be parsed from the request.
  • rez.Validator: A validator for the route or middleware.
  • api.Operation: The operation (route only).
  • rez.MiddlewareNext: Invoke the next handler (middleware only).

There are a few other methods to get other injectable values.

  1. Use rez.Site.Scope to set global values and providers.
  2. Implement rez.Injectable.
  3. Use rez.Router.DefineBody(bodies...) to define types that will only be used as arguments that should come from the request body.
  4. Use rez.Router.DefinePath(paths...) to define types that will only be used as arguments that should come from the request path parameters.
  5. Use rez.Router.DefineQuery(queries...) to define types that will only be used as arguments that should come from the request query parameters.
  6. Use rez.Router.DefineHeader(headers...) to define types that will only be used as arguments that should come from the request headers.
  7. Use *deps.Scope as an argument in middleware and Set or Provide other values that the following handlers will be able to receive.

Router

The rez.Router is a wrapper of chi.Router where instead of http.Handers and http.HandlerFunc you pass in a func(args) results which gets its arguments injected, and in the case of middleware is able to provide injected values for routes in the router. The function argument and result types are also inspected to build the OpenAPI documentation.

Middleware

Middleware in rez is also a dependency injected function. The middleware can return nothing or can return an error which if non-nil will be sent as the response. The middleware has a special injected value rez.MiddlewareNext which is a function to call if we want to call the next handler. Any arguments or return types that are identified as headers, queries, paths, request bodies, or responses are added as those objects in all routes that are in the router using the middleware.

Example:

// site.Use(authMiddleware)
func authMiddleware(next rez.MiddlewareNext, r *http.Request) *rez.Unauthorized[string] {
  // Accessing headers this way doesn't add it as a parameter to all routes that use the middleware.
  auth := r.Header.Get("Authorization")
  if auth == "" {
    return rez.NewUnauthorized("No access")
  }
  next()
  return nil
}

You can also pass down injectable values to all middlewares and routes which are defined after middleware by setting the value on the scope.

type User struct { ID int }
// site.Use(authMiddleware)
func authMiddleware(next rez.MiddlewareNext, s *deps.Scope) {
  // authenticate user and return error, if successful apply the user to the scope.
  s.Set(User{ID: 23})
  next()
}
type Task struct { ID int, Name string, Done bool }
// set.Get("/tasks", getTasks)
func getTasks(user User) Task[] {
  // get tasks the user can see, we only get here if authMiddleware called next
  return []Task{}
}

As mentioned what you reference with middleware could add to the operations that follow. This middleware is an example of authentication where the token is foolishly sent in the query string. All operations that follow will have the specified security scheme, accept token as a query parameter, and could respond with rez.Unauthorized[string].

type Auth struct { Token string }

type AuthMiddleware func(s *deps.Scope, next rez.MiddlewareNext, q rez.Query[Auth]) *rez.Unauthorized[string]
// All routes which use this middleware accept this type of security
func (auth AuthMiddleware) APIOperationUpdate(op *api.Operation) {
  op.Security = append(op.Security, map[string][]string{"queryAuth": {}})
}

var authMiddleware AuthMiddleware = func(s *deps.Scope, next rez.MiddlewareNext, q rez.Query[Auth]) *rez.Unauthorized[string] {
  if q.Value.Token == "" {
    return rez.NewUnauthorized("No access")
  }
  s.Set(q.Value)
  next()
  return nil
}
func echoToken(token Auth) Auth {
  return token
}

// Usage
site.Open.AddSecurity("queryAuth", &api.Security{
  Type: api.SecurityTypeApiKey,
  Name: "token",
  In:   api.ParameterInQuery,
})
site.Use(authMiddleware)
site.Get("/token", echoToken)

Inspection

Function arguments are inspected to determine what path parameters, query parameters, headers, and body is used by a route. See Dependency Injection for more details on that. The types detected are converted into api objects and are added to the OpenAPI document and referenced in the path & operations in the path. The function return arguments are inspected for possible responses - most of the time these return types will be pointers for routes which can have multiple response types (or no specific response type). If the return type implements rez.HasStatus that is where the status code is pulled from. If the return type does not it's assumed to be a possible OK (200) result. The schemas built from the argument and return types are built once and can be controlled using various functions and interfaces. If the type is a struct then json and api tags can control the field visibility or schema options. See Documentation for additional details on how to control the documentation & validation that is generated.

Validation

Validation in rez is done if enabled and only for certain schema fields and after the data is marshalled into values. So any invalid type errors will not be triggered by the validation but when the JSON is parsed. General validation options can be applied per type, validation can be enabled or disabled for any router, and types can have custom validation code that takes over the validation process or runs after the validation process. If validation fails the error is returned to the user. How those validations are sent to the user can be controlled by calling rez.Router.SetErrorHandler.

  • rez.Router.EnabledValidation(bool) enables or disables validation in this router and any sub-routers created after this call. By default validation is not enabled.
  • rez.Router.SetValidationOptions(any,ValidationOptions) sets the validation options for the given type, which controls if validation is skipped, if format is enforced, or if specifying deprecated values triggers a validation error.
  • rez.CanValidateFull if a type implements this it handles all validation logic.
  • rez.CanValidatePost if a type implements this it will do additional validation logic after other validation logic has been done.
  • rez.Injectable if a type implements this it must implement an APIValidate method.

The following schema fields are used during validation:

  • MultipleOf, Maximum, Minimum, ExclusiveMaximum, ExclusiveMinimum are used for any int or float types.
  • MaxLength, MinLength are used for string types.
  • Deprecated, Nullable, Pattern, Format, Enum, OneOf, AllOf, AnyOf, Not are used for all types.
  • MinItems, MaxItems, Items, UniqueItems are used for array and slice types.
  • MinProperties, MaxProperties, AdditionalProperties are used for map types.
  • Properties, Required are used for struct types.

Documentation

Documentation is control by various ways on the types themselves or through router methods.

  • api.HasName A type's documented name is the name of the type in the GO code, but there might be collisions. If there are collisions the OpenAPI built will have schema names that include the types pkg path to be unique. To avoid those potentially lengthy names you can implement api.HasName like so:
// tasks folder
type Search struct { Name string }
func (Search) APIName() string { return "TaskSearch" }
  • api.Description A request or response's description can be specified on tyhe type by implementing this interface. Using the code above.
func (Search) APIDescription() string { return "This is used to determine what Tasks to return." }
  • api.HasBaseSchema A type's schema will be dynamically determined, but implementing this interface will provide the schema building logic with a starting point. You can define the preferred schema properties.
func (Search) APIBaseSchema() *api.Schema {
  return &api.Schema{
    Title:       "Task Search",
    Description: "This is used to determine what Tasks to return.",
    Example      api.Any(Search{Name: "homework"}),
  }
}
  • api.HasFullSchema A type's schema will only be determined by what's returned, no further inspection is done. This is useful if you want to use some of the built-in struct types that support different formats.
type Timestamp time.Time
func (Timestamp) APIFullSchema() *api.Schema {
  return &api.Schema{
    Type:    api.DataTypeString,
    Format:  "date-time",
    Pattern: `\\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d+\d\d:\d\d`,
    Example: api.Any("2018-11-13T20:20:39+00:00"),
  }
}
  • api.HasEnum A type can accept only a handful of values.
type TodoAction string
const (
  TodoActionArchive  TodoAction = "archive"
  TodoActionDelete   TodoAction = "delete"
  TodoActionComplete TodoAction = "complete"
)
func (TodoAction) APIEnum() []any {
  return []any{TodoActionArchive, TodoActionDelete, TodoActionComplete}
}
  • api.HasExamples A type can provide several named examples for a given content type.
func (Search) APIExamples(contentType api.ContentType) api.Examples {
  return api.Examples{
    "All tasks": api.Example{
      Summary: "This search will return all tasks the user can see.",
      Value:   api.Any(Search{}),
    },
    "Tasks with 'homework' in the name": api.Example{
      Summary: "This search will return all tasks with 'homework' in the name.",
      Value:   api.Any(Search{Name: "homework"}),
    },
  }
}
  • api.HasExample A type that can provide a single example for a type.
func (Search) APIExample() *any {
  return api.Any(Search{Name: "homework"})
}
  • api.HasOperation A route function that has the operation fully defined here and no inspection needs to be done on the arguments or return types.
type GetTask func(id string) *Task
func (GetTask) APIOperation() api.Operation {
  return api.Operation{
    Tags:        []string{"Task"},
    Summary:     "Get the task with the given ID",
    OperationID: "GET_TASK_BY_ID",
    Parameters:  []api.Parameter{{
      Name:     "id",
      In:       api.ParameterInPath,
      Required: true,
      Schema:   &api.Schema{Type: api.TypeString},
      Example:  api.Any("87y34"),
    }},
    Responses:  api.Responses{
      "200":    &api.Response{
        Description: "The task exists and has these values",
        Content:     api.Contents{
          api.ContentTypeJSON: &api.MediaType{
            Schema: site.Open.GetSchema(reflect.TypeOf(Task{})),
          },
        },
      },
    },
  }
}
  • api.HasOperationUpdate A route function that modifies the operation inspected after its done inspection.
type GetTask func(id string) *Task
func (GetTask) APIOperationUpdate(op *api.Operation) {
  op.OperationID = "GET_TASK_BY_ID"
}
  • rez.Site.Open is a reference to api.Builder which has a Document field which can be modified. This is the base document to use before building the final api.Document.
  • rez.Router has a few methods to assist in documentation:
    • GetOperations() *api.Operation returns a reference to the operation template that has accumulated at this point in the router. Sub routers inherit this. Middlewares add to it.
    • SetOperations(api.Operation) sets the operation template in its entirety, overwriting what has been built so far.
    • UpdateOperations(api.Operation) merges in the fields set on the given operation into the operation template of this router.
    • GetPath(pattern) *api.Path returns a reference to the path with the given pattern. Defining methods will add operations to this path. If the path has not been defined yet nil is returned.
    • CreatePath(pattern) *api.Path returns a reference to the path with the given pattern, creating it if need be.
    • UpdatePath(pattern, api.Path) merges in the fields set on the given path with the path defined at the given pattern - creating it if need be.
    • SetTags(tags []string) sets the tags on the operation template to this value.
    • AddTags(tags) adds the tags to the operation template.
    • SetResponses(api.Responses) sets the responses for all operations defined after. This overwrites any responses specified previously by the user or middlewares.
    • AddResponses(api.Responses) adds the responses to the operation template.
    • AddResponse(code, api.Response) adds the response to the operation template.
    • HandleFunc(pattern, fn, ...api.Operation) *api.Path can accept zero or more operation definitions to merge into the operations defined at this path - and the reference to the path at the pattern is returned.
    • "method"(pattern, fn, ...api.Operation) *api.Operation is a method with the name of any of the HTTP methods which adds this method to the path with the pattern and merges in any given operations with the operation template and then returns the reference to the final built operation for this route.
  • Struct tags. Fields on a struct can specify the api tag which is a comma-delimited list of key=value or flags. If you need to use a comma in a value you can escape it like \,.
    • title ex: api:"title=A person's address" (see api.Schema.Title)
    • desc or description ex: api:"desc=The ten digit home phone number." (see api.Schema.Description)
    • format ex: api:"format=email" (see api.Schema.Format)
    • pattern ex: api:"pattern=\d+" (see api.Schema.Pattern)
    • deprecated ex: api:"deprecated" (see api.Schema.Deprecated)
    • required ex: api:"required" (see api.Schema.Nullable)
    • null or nullable ex: api:"null" (see api.Schema.Nullable)
    • readonly ex: api:"readonly" (see api.Schema.ReadOnly)
    • writeonly ex: api:"writeonly" (see api.Schema.WriteOnly)
    • enum ex: api:"enum=1|2|3" (see api.Schema.Enum)
    • minlength ex: api:"minlength=6" (see api.Schema.MinLength)
    • maxlength ex: api:"maxlength=6" (see api.Schema.MaxLength)
    • minitems ex: api:"minitems=6" (see api.Schema.MinItems)
    • maxitems ex: api:"maxitems=6" (see api.Schema.MaxItems)
    • multipleof ex: api:"multipleof=2" (see api.Schema.MultipleOf)
    • min or minimum ex: api:"min=1" (see api.Schema.Minimum)
    • max or maximum ex: api:"max=1" (see api.Schema.Maximum)
    • exclusivemaximum or exclusivemax ex: api:"exclusivemax=true" (see api.Schema.ExclusiveMaximum)
    • exclusiveminimum or exclusivemin ex: api:"exclusivemin" (see api.Schema.ExclusiveMinimum)

Site

rez.Site is the implementation of router that must be created with rez.New(chi.Router). Site has a few additional methods:

  • BuildDocument() *api.Document returns the built document based on the routes and middlewares defined thus far.
  • BuildJSON() []byte calls BuildDocument and marshals it to JSON.
  • ServeOpenJSON(patten) serves the BuildJSON to a GET route at the defined pattern. This gets called by the other Serve document related endpoints if it was not called yet with a default pattern of openapi3.json.
  • ServeSwaggerUI(pattern,options) serves an HTML page at the given pattern which presents the SwaggerUI which points to the OpenAPI document JSON.
  • ServeRedoc(pattern) serves an HTML page at the given pattern which presents the Redoc which points to the OpenAPI document JSON.
  • Listen(addr) starts the site and blocks until it stops.
  • Run() starts the site but looks at the CLI args for a --host argument to specify the port. It defaults to :80.
  • PrintPaths() prints an ASCII grid to the console with the paths described in the site at this point in time. Includes the "Method", "URL", and "About" if any summary or descriptions are given. Example output:
┌───────┬───────────┬────────────────────┐
│Method │URL        │About               │
├───────┼───────────┼────────────────────┤
│GET    │/task/{id} │Get task by id      │
├───────┼───────────┼────────────────────┤
│DELETE │/task/{id} │Delete task by id   │
├───────┼───────────┼────────────────────┤
│GET    │/auth      │Get current session │
├───────┼───────────┼────────────────────┤
│POST   │/auth      │Login               │
├───────┼───────────┼────────────────────┤
│DELETE │/auth      │Logout              │
└───────┴───────────┴────────────────────┘

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrUnsupportedType = errors.New("unsupported type")
View Source
var ScopeKey = scopeKey{"RezScope"}

Functions

func Validate

func Validate(givenSchema *api.Schema, rawValue any, v *Validator)

Validates a value against a schema.

func ValidateInjectable

func ValidateInjectable(inj Injectable, scope *deps.Scope) error

Validates the injectable by pulling the validator and operation off of the scope and calling APIValidate. If there are any validation errors the validator (which implements error) is returned.

Types

type Accepted

type Accepted[V any] struct {
	Result V
}

A 202 response.

func NewAccepted

func NewAccepted[V any](result V) *Accepted[V]

func (Accepted[V]) APIName added in v0.3.4

func (err Accepted[V]) APIName() string

func (Accepted[V]) APISchemaType added in v0.3.4

func (err Accepted[V]) APISchemaType() any

func (Accepted[V]) HTTPStatus

func (err Accepted[V]) HTTPStatus() int

func (Accepted[V]) HTTPStatuses

func (err Accepted[V]) HTTPStatuses() []int

func (Accepted[V]) MarshalJSON

func (err Accepted[V]) MarshalJSON() ([]byte, error)

func (*Accepted[V]) UnmarshalJSON

func (err *Accepted[V]) UnmarshalJSON(data []byte) error

type BadRequest

type BadRequest[V any] struct {
	Result V
}

A 400 response.

func NewBadRequest

func NewBadRequest[V any](result V) *BadRequest[V]

func (BadRequest[V]) APIName added in v0.3.4

func (err BadRequest[V]) APIName() string

func (BadRequest[V]) APISchemaType added in v0.3.4

func (err BadRequest[V]) APISchemaType() any

func (BadRequest[V]) Error

func (err BadRequest[V]) Error() string

func (BadRequest[V]) HTTPStatus

func (err BadRequest[V]) HTTPStatus() int

func (BadRequest[V]) HTTPStatuses

func (err BadRequest[V]) HTTPStatuses() []int

func (BadRequest[V]) MarshalJSON

func (err BadRequest[V]) MarshalJSON() ([]byte, error)

func (*BadRequest[V]) UnmarshalJSON

func (err *BadRequest[V]) UnmarshalJSON(data []byte) error

type Body

type Body[B any] struct {
	Value B
}

A function parameter that is injected with the request body.

func (Body[B]) APIRequestTypes

func (b Body[B]) APIRequestTypes() RequestTypes

func (Body[B]) APIValidate

func (p Body[B]) APIValidate(op *api.Operation, v *Validator)

func (*Body[B]) ProvideDynamic

func (b *Body[B]) ProvideDynamic(scope *deps.Scope) error

type CanSend

type CanSend interface {
	HTTPSend(w http.ResponseWriter) error
}

A response which has custom sending logic.

type CanValidateFull

type CanValidateFull interface {
	FullValidate(v *Validator)
}

If a type implements this interface then it handles all validation for the type.

type CanValidatePost

type CanValidatePost interface {
	PostValidate(v *Validator)
}

If a type implements this interface then it handles validation after the normal validation process has occurred.

type Conflict

type Conflict[V any] struct {
	Result V
}

A 409 response.

func NewConflict

func NewConflict[V any](result V) *Conflict[V]

func (Conflict[V]) APIName added in v0.3.4

func (err Conflict[V]) APIName() string

func (Conflict[V]) APISchemaType added in v0.3.4

func (err Conflict[V]) APISchemaType() any

func (Conflict[V]) Error

func (err Conflict[V]) Error() string

func (Conflict[V]) HTTPStatus

func (err Conflict[V]) HTTPStatus() int

func (Conflict[V]) HTTPStatuses

func (err Conflict[V]) HTTPStatuses() []int

func (Conflict[V]) MarshalJSON

func (err Conflict[V]) MarshalJSON() ([]byte, error)

func (*Conflict[V]) UnmarshalJSON

func (err *Conflict[V]) UnmarshalJSON(data []byte) error

type Created

type Created[V any] struct {
	Result V
}

A 201 response.

func NewCreated

func NewCreated[V any](result V) *Created[V]

func (Created[V]) APIName added in v0.3.4

func (err Created[V]) APIName() string

func (Created[V]) APISchemaType added in v0.3.4

func (err Created[V]) APISchemaType() any

func (Created[V]) HTTPStatus

func (err Created[V]) HTTPStatus() int

func (Created[V]) HTTPStatuses

func (err Created[V]) HTTPStatuses() []int

func (Created[V]) MarshalJSON

func (err Created[V]) MarshalJSON() ([]byte, error)

func (*Created[V]) UnmarshalJSON

func (err *Created[V]) UnmarshalJSON(data []byte) error

type ErrorHandler

type ErrorHandler = func(err error, response http.ResponseWriter, request *http.Request, scope *deps.Scope) (bool, error)

A function which handles the error and returns true or returns false for the error to be handled by default behavior.

type Forbidden

type Forbidden[V any] struct {
	Result V
}

A 403 response.

func NewForbidden

func NewForbidden[V any](result V) *Forbidden[V]

func (Forbidden[V]) APIName added in v0.3.4

func (err Forbidden[V]) APIName() string

func (Forbidden[V]) APISchemaType added in v0.3.4

func (err Forbidden[V]) APISchemaType() any

func (Forbidden[V]) Error

func (err Forbidden[V]) Error() string

func (Forbidden[V]) HTTPStatus

func (err Forbidden[V]) HTTPStatus() int

func (Forbidden[V]) HTTPStatuses

func (err Forbidden[V]) HTTPStatuses() []int

func (Forbidden[V]) MarshalJSON

func (err Forbidden[V]) MarshalJSON() ([]byte, error)

func (*Forbidden[V]) UnmarshalJSON

func (err *Forbidden[V]) UnmarshalJSON(data []byte) error

type HandledError

type HandledError interface {
	error
	// Handle the error
	Handle(response http.ResponseWriter, request *http.Request, scope *deps.Scope) error
}

An error type which has custom error handling.

type HasContentType

type HasContentType interface {
	HTTPContentType() string
}

A response which has a custom content type.

type HasStatus

type HasStatus interface {
	// The status of this particular response
	HTTPStatus() int
	// All possible statuses for this response type
	HTTPStatuses() []int
}

A response type that has a known status but could return more than one status. HTTPStatus is used when returning a response and HTTPStatuses is used for documentation.

type Header[H any] struct {
	Value H
}

A function parameter that is injected with the request headers.

func (Header[H]) APIRequestTypes

func (h Header[H]) APIRequestTypes() RequestTypes

func (Header[H]) APIValidate

func (h Header[H]) APIValidate(op *api.Operation, v *Validator)

func (*Header[H]) ProvideDynamic

func (r *Header[H]) ProvideDynamic(scope *deps.Scope) error

type Injectable

type Injectable interface {
	deps.Dynamic

	// Return the types for any request types in this injectable.
	APIRequestTypes() RequestTypes

	// Do validation for this type.
	APIValidate(op *api.Operation, v *Validator)
}

A type which has one or more injectable request types. This is how the dependency injected functions are inspected for types which are added to the Open API document.

type InternalErrorHandler

type InternalErrorHandler = func(err error)

A function which handles an error that couldn't be sent to the client.

type InternalServerError

type InternalServerError[V any] struct {
	Result V
}

A 500 response.

func NewInternalServerError

func NewInternalServerError[V any](result V) *InternalServerError[V]

func (InternalServerError[V]) APIName added in v0.3.4

func (err InternalServerError[V]) APIName() string

func (InternalServerError[V]) APISchemaType added in v0.3.4

func (err InternalServerError[V]) APISchemaType() any

func (InternalServerError[V]) Error

func (err InternalServerError[V]) Error() string

func (InternalServerError[V]) HTTPStatus

func (err InternalServerError[V]) HTTPStatus() int

func (InternalServerError[V]) HTTPStatuses

func (err InternalServerError[V]) HTTPStatuses() []int

func (InternalServerError[V]) MarshalJSON

func (err InternalServerError[V]) MarshalJSON() ([]byte, error)

func (*InternalServerError[V]) UnmarshalJSON

func (err *InternalServerError[V]) UnmarshalJSON(data []byte) error

type MiddlewareNext

type MiddlewareNext func()

The function to forward middleware onto the next handler. To change the request or response refer to them in the injectable function arguments as a pointer and change the value.

func NewMiddlewareNext

func NewMiddlewareNext(h http.Handler, scope *deps.Scope) MiddlewareNext

Creates a new MiddlewareNext given a handler and scope.

type Moved added in v0.3.4

type Moved[V any] struct {
	Result V
}

A 301 response.

func NewMoved added in v0.3.4

func NewMoved[V any](result V) *Moved[V]

func (Moved[V]) APIName added in v0.3.4

func (err Moved[V]) APIName() string

func (Moved[V]) APISchemaType added in v0.3.4

func (err Moved[V]) APISchemaType() any

func (Moved[V]) HTTPStatus added in v0.3.4

func (err Moved[V]) HTTPStatus() int

func (Moved[V]) HTTPStatuses added in v0.3.4

func (err Moved[V]) HTTPStatuses() []int

func (Moved[V]) MarshalJSON added in v0.3.4

func (err Moved[V]) MarshalJSON() ([]byte, error)

func (*Moved[V]) UnmarshalJSON added in v0.3.4

func (err *Moved[V]) UnmarshalJSON(data []byte) error

type None

type None struct{}

An empty type to signal that a request has no parameters or body.

type NotFound

type NotFound[V any] struct {
	Result V
}

A 404 response.

func NewNotFound

func NewNotFound[V any](result V) *NotFound[V]

func (NotFound[V]) APIName added in v0.3.4

func (err NotFound[V]) APIName() string

func (NotFound[V]) APISchemaType added in v0.3.4

func (err NotFound[V]) APISchemaType() any

func (NotFound[V]) Error

func (err NotFound[V]) Error() string

func (NotFound[V]) HTTPStatus

func (err NotFound[V]) HTTPStatus() int

func (NotFound[V]) HTTPStatuses

func (err NotFound[V]) HTTPStatuses() []int

func (NotFound[V]) MarshalJSON

func (err NotFound[V]) MarshalJSON() ([]byte, error)

func (*NotFound[V]) UnmarshalJSON

func (err *NotFound[V]) UnmarshalJSON(data []byte) error

type NotImplemented

type NotImplemented[V any] struct {
	Result V
}

A 501 response.

func NewNotImplemented

func NewNotImplemented[V any](result V) *NotImplemented[V]

func (NotImplemented[V]) APIName added in v0.3.4

func (err NotImplemented[V]) APIName() string

func (NotImplemented[V]) APISchemaType added in v0.3.4

func (err NotImplemented[V]) APISchemaType() any

func (NotImplemented[V]) Error

func (err NotImplemented[V]) Error() string

func (NotImplemented[V]) HTTPStatus

func (err NotImplemented[V]) HTTPStatus() int

func (NotImplemented[V]) HTTPStatuses

func (err NotImplemented[V]) HTTPStatuses() []int

func (NotImplemented[V]) MarshalJSON

func (err NotImplemented[V]) MarshalJSON() ([]byte, error)

func (*NotImplemented[V]) UnmarshalJSON

func (err *NotImplemented[V]) UnmarshalJSON(data []byte) error

type OK

type OK[V any] struct {
	Result V
}

A 200 response.

func NewOK

func NewOK[V any](result V) *OK[V]

func (OK[V]) APIName added in v0.3.4

func (err OK[V]) APIName() string

func (OK[V]) APISchemaType added in v0.3.4

func (err OK[V]) APISchemaType() any

func (OK[V]) HTTPStatus

func (err OK[V]) HTTPStatus() int

func (OK[V]) HTTPStatuses

func (err OK[V]) HTTPStatuses() []int

func (OK[V]) MarshalJSON

func (err OK[V]) MarshalJSON() ([]byte, error)

func (*OK[V]) UnmarshalJSON

func (err *OK[V]) UnmarshalJSON(data []byte) error

type Path

type Path[P any] struct {
	Value P
}

A function parameter that is injected with path parameters.

func (Path[P]) APIRequestTypes

func (p Path[P]) APIRequestTypes() RequestTypes

func (Path[P]) APIValidate

func (p Path[P]) APIValidate(op *api.Operation, v *Validator)

func (*Path[P]) ProvideDynamic

func (r *Path[P]) ProvideDynamic(scope *deps.Scope) error

type PaymentRequired added in v0.3.4

type PaymentRequired[V any] struct {
	Result V
}

A 402 response.

func NewPaymentRequired added in v0.3.4

func NewPaymentRequired[V any](result V) *PaymentRequired[V]

func (PaymentRequired[V]) APIName added in v0.3.4

func (err PaymentRequired[V]) APIName() string

func (PaymentRequired[V]) APISchemaType added in v0.3.4

func (err PaymentRequired[V]) APISchemaType() any

func (PaymentRequired[V]) Error added in v0.3.4

func (err PaymentRequired[V]) Error() string

func (PaymentRequired[V]) HTTPStatus added in v0.3.4

func (err PaymentRequired[V]) HTTPStatus() int

func (PaymentRequired[V]) HTTPStatuses added in v0.3.4

func (err PaymentRequired[V]) HTTPStatuses() []int

func (PaymentRequired[V]) MarshalJSON added in v0.3.4

func (err PaymentRequired[V]) MarshalJSON() ([]byte, error)

func (*PaymentRequired[V]) UnmarshalJSON added in v0.3.4

func (err *PaymentRequired[V]) UnmarshalJSON(data []byte) error

type Query

type Query[Q any] struct {
	Value Q
}

A function parameter that is injected with query parameters.

func (Query[Q]) APIRequestTypes

func (q Query[Q]) APIRequestTypes() RequestTypes

func (Query[Q]) APIValidate

func (p Query[Q]) APIValidate(op *api.Operation, v *Validator)

func (*Query[Q]) ProvideDynamic

func (r *Query[Q]) ProvideDynamic(scope *deps.Scope) error

type Request

type Request[B any, P any, Q any] struct {
	Body  B
	Path  P
	Query Q
}

A function parameter that is injected with the body, path, and query parameters.

func (Request[B, P, Q]) APIRequestTypes

func (r Request[B, P, Q]) APIRequestTypes() RequestTypes

func (Request[B, P, Q]) APIValidate

func (p Request[B, P, Q]) APIValidate(op *api.Operation, v *Validator)

func (*Request[B, P, Q]) ProvideDynamic

func (r *Request[B, P, Q]) ProvideDynamic(scope *deps.Scope) error

type RequestTypes

type RequestTypes struct {
	Body   reflect.Type
	Path   reflect.Type
	Query  reflect.Type
	Header reflect.Type
}

A value that holds types, so the dependency injection system can pick up on the types that represent the parts of a request.

type Result

type Result[V any] struct {
	Status int
	Value  V
}

A custom status response. The documentation will not be able to report on the status of this type, you need to use one of the provided types or define your own implementor of HasStatus.

func NewResult

func NewResult[V any](status int, result V) *Result[V]

func (Result[V]) APIName added in v0.3.4

func (err Result[V]) APIName() string

func (Result[V]) APISchemaType added in v0.3.4

func (err Result[V]) APISchemaType() any

func (Result[V]) HTTPStatus

func (se Result[V]) HTTPStatus() int

func (Result[V]) HTTPStatuses

func (se Result[V]) HTTPStatuses() []int

func (Result[V]) MarshalJSON

func (se Result[V]) MarshalJSON() ([]byte, error)

func (*Result[V]) UnmarshalJSON

func (se *Result[V]) UnmarshalJSON(data []byte) error

type Router

type Router interface {
	ValidationProvider

	// The internal chi.Router
	Chi() chi.Router

	// The url of the router at this point.
	URL() string

	// Sets the error handler at this router and all sub routers created after this is set.
	SetErrorHandler(handler ErrorHandler)

	// Sets the handler for errors we received outside of responding to the client.
	SetInternalErrorHandler(handle InternalErrorHandler)

	// Handles the given error if its a HandledError, is handled by the error handler, or is handled with default behavior.
	HandleError(err error, response http.ResponseWriter, request *http.Request, scope *deps.Scope) error

	// Enables or disables validation for all routes in this router or sub routers created after this is set.
	// By default validation is not enabled.
	EnableValidation(enabled bool)

	// Sets the validation options for the type or value's type.
	SetValidationOptions(valueOrType any, options ValidationOptions)

	// Adds the types of the given values as injectable request bodies. This avoids
	// the necessity of rez.Body or rez.Request. If any of the values/types
	// have already been defined this will cause a panic.
	DefineBody(bodies ...any)

	// Adds the types of the given values as injectable parameters. This avoids
	// the necessity of rez.Param or rez.Request. If any of the values/types
	// have already been defined this will cause a panic.
	DefinePath(params ...any)

	// Adds the types of the given values as injectable query parameters. This avoids
	// the necessity of rez.Query or rez.Request. If any of the values/types
	// have already been defined this will cause a panic.
	DefineQuery(queries ...any)

	// Adds the types of the given values as injectable header values. This avoids
	// the necessity of rez.Header. If any of the values/types
	// have already been defined this will cause a panic.
	DefineHeader(headers ...any)

	// Gets the base operation which has all inherited tags and responses set at the current router.
	GetOperations() *api.Operation

	// Sets the base operation. All sub routes will inherit the properties on the base operation.
	SetOperations(op api.Operation)

	// Updates the base operation (merges in given properties into existing base operation).
	// All sub routes will inherit the properties on the base operation.
	UpdateOperations(op api.Operation)

	// Gets the path defined at the given pattern, if any
	GetPath(pattern string) *api.Path

	// Gets the path define at the given pattern, creating it if need be.
	CreatePath(pattern string) *api.Path

	// Merges the path definition into the path
	UpdatePath(pattern string, path api.Path)

	// Sets the tags for all child routes starting at this router.
	// This is similar to router.SetOperation(api.Operation{Tags: tags}).
	SetTags(tags []string)

	// Adds the tags for all child routes starting at this router
	AddTags(tags []string)

	// Sets the responses for all child routes starting at this router
	// This is similar to router.SetOperation(api.Operation{Responses: responses}).
	SetResponses(responses api.Responses)

	// Adds responses for all child routes starting at this router.
	AddResponses(responses api.Responses)

	// Adds a response for all child routes starting at this router.
	AddResponse(code string, response api.Response)

	// Gets or creates a scope for the given request if it doesn't exist yet.
	GetScope(response http.ResponseWriter, request *http.Request) (scope *deps.Scope, freeScope bool)

	// Use appends one or more middlewares onto the Router stack.
	// A middleware is a dependency injectable function.
	// The function has access to the request, response, scope, and any other
	// injectable request values. The values applied to the scope here will
	// be passed down to lower routes and can be injected in their functions.
	// If the function has problems injecting arguments or returns any errors
	// then the next handler in the stack will not be invoked and the error
	// will be handled like any other error.
	Use(middlewares ...any)

	// With adds inline middlewares for an endpoint handler and returns a
	// new router at the same URL.
	With(middlewares ...any) Router

	// Group adds a new inline-Router along the current routing
	// path, with a fresh middleware stack for the inline-Router.
	Group(fn func(r Router)) Router

	// Route mounts a sub-Router along a `pattern` string.
	Route(pattern string, fn func(r Router)) Router

	// Handle and HandleFunc adds routes for `pattern` that matches all HTTP methods.
	HandleFunc(pattern string, fn any, operations ...api.Operation) *api.Path

	// Method and MethodFunc adds routes for `pattern` that matches
	// the `method` HTTP method.
	MethodFunc(method, pattern string, fn any, operations ...api.Operation) RouterOperation

	// HTTP-method routing along `pattern`
	Connect(pattern string, fn any)
	Delete(pattern string, fn any, operations ...api.Operation) RouterOperation
	Get(pattern string, fn any, operations ...api.Operation) RouterOperation
	Head(pattern string, fn any, operations ...api.Operation) RouterOperation
	Options(pattern string, fn any, operations ...api.Operation) RouterOperation
	Patch(pattern string, fn any, operations ...api.Operation) RouterOperation
	Post(pattern string, fn any, operations ...api.Operation) RouterOperation
	Put(pattern string, fn any, operations ...api.Operation) RouterOperation
	Trace(pattern string, fn any, operations ...api.Operation) RouterOperation

	// NotFound defines a handler to respond whenever a route could
	// not be found.
	NotFound(fn any)

	// MethodNotAllowed defines a handler to respond whenever a method is
	// not allowed.
	MethodNotAllowed(fn any)
}

Router with OpenAPI integration and dependency injection

type RouterOperation added in v0.2.0

type RouterOperation interface {
	// The operation documentation.
	Operation() *api.Operation

	// The router of the operation
	Router() Router

	// Adds the given type/instance as an input (body, param, query, header) to the operation.
	Input(input ...any)

	// Adds the given type/instance as a response type to the operation.
	Output(output ...any)
}

A router operation

type ServiceUnavailable

type ServiceUnavailable[V any] struct {
	Result V
}

A 503 response.

func NewServiceUnavailable

func NewServiceUnavailable[V any](result V) *ServiceUnavailable[V]

func (ServiceUnavailable[V]) APIName added in v0.3.4

func (err ServiceUnavailable[V]) APIName() string

func (ServiceUnavailable[V]) APISchemaType added in v0.3.4

func (err ServiceUnavailable[V]) APISchemaType() any

func (ServiceUnavailable[V]) Error

func (err ServiceUnavailable[V]) Error() string

func (ServiceUnavailable[V]) HTTPStatus

func (err ServiceUnavailable[V]) HTTPStatus() int

func (ServiceUnavailable[V]) HTTPStatuses

func (err ServiceUnavailable[V]) HTTPStatuses() []int

func (ServiceUnavailable[V]) MarshalJSON

func (err ServiceUnavailable[V]) MarshalJSON() ([]byte, error)

func (*ServiceUnavailable[V]) UnmarshalJSON

func (err *ServiceUnavailable[V]) UnmarshalJSON(data []byte) error

type Site

type Site struct {
	Open      *api.Builder
	Scope     *deps.Scope
	ServeJSON bool
	ServeXML  bool
	// contains filtered or unexported fields
}

The main router for rez. Can only be created with rez.New. All sub routers created are also a Site.

func New

func New(router chi.Router) *Site

Creates a new site given the base chi.Router.

func (*Site) AddResponse

func (site *Site) AddResponse(code string, response api.Response)

Adds responses for all child routes starting at this router.

func (*Site) AddResponses

func (site *Site) AddResponses(responses api.Responses)

Adds responses for all child routes starting at this router.

func (*Site) AddTags

func (site *Site) AddTags(tags []string)

Adds the tags for all child routes starting at this router

func (*Site) BuildDocument

func (site *Site) BuildDocument() *api.Document

func (*Site) BuildJSON

func (site *Site) BuildJSON() []byte

func (Site) Chi

func (site Site) Chi() chi.Router

The internal chi.Router

func (*Site) Connect

func (site *Site) Connect(pattern string, fn any)

func (*Site) CreatePath

func (site *Site) CreatePath(pattern string) *api.Path

Gets the path define at the given pattern, creating it if need be.

func (*Site) DefineBody

func (site *Site) DefineBody(bodies ...any)

Adds the types of the given values as injectable request bodies. This avoids the necessity of rez.Body or rez.Request. If any of the values/types have already been defined this will cause a panic.

func (*Site) DefineHeader

func (site *Site) DefineHeader(bodies ...any)

Adds the types of the given values as injectable header values. This avoids the necessity of rez.Header. If any of the values/types have already been defined this will cause a panic.

func (*Site) DefinePath

func (site *Site) DefinePath(paths ...any)

Adds the types of the given values as injectable path parameters. This avoids the necessity of rez.Param or rez.Request. If any of the values/types have already been defined this will cause a panic.

func (*Site) DefineQuery

func (site *Site) DefineQuery(bodies ...any)

Adds the types of the given values as injectable query parameters. This avoids the necessity of rez.Query or rez.Request. If any of the values/types have already been defined this will cause a panic.

func (*Site) Delete

func (site *Site) Delete(pattern string, fn any, operations ...api.Operation) RouterOperation

func (*Site) EnableValidation

func (site *Site) EnableValidation(enabled bool)

Enables or disables validation for all routes in this router or sub routers created after this is set. By default validation is not enabled.

func (*Site) Get

func (site *Site) Get(pattern string, fn any, operations ...api.Operation) RouterOperation

func (*Site) GetOperations

func (site *Site) GetOperations() *api.Operation

Gets the base operation which has all inherited tags and responses set at the current router.

func (*Site) GetPath

func (site *Site) GetPath(pattern string) *api.Path

Gets the path defined at the given pattern, if any

func (*Site) GetScope

func (site *Site) GetScope(response http.ResponseWriter, request *http.Request) (requestScope *deps.Scope, freeScope bool)

Gets or creates a scope for the given request if it doesn't exist yet.

func (*Site) Group

func (site *Site) Group(fn func(r Router)) Router

Group adds a new inline-Router along the current routing path, with a fresh middleware stack for the inline-Router.

func (*Site) HandleError

func (site *Site) HandleError(err error, response http.ResponseWriter, request *http.Request, scope *deps.Scope) error

Handles the given error if its a HandledError, is handled by the error handler, or is handled with default behavior.

func (*Site) HandleFunc

func (site *Site) HandleFunc(pattern string, fn any, operations ...api.Operation) *api.Path

Handle and HandleFunc adds routes for `pattern` that matches all HTTP methods.

func (*Site) Head

func (site *Site) Head(pattern string, fn any, operations ...api.Operation) RouterOperation

func (*Site) Listen

func (site *Site) Listen(addr string)

func (*Site) MethodFunc

func (site *Site) MethodFunc(method string, pattern string, fn any, operations ...api.Operation) RouterOperation

Method and MethodFunc adds routes for `pattern` that matches the `method` HTTP method.

func (*Site) MethodNotAllowed

func (site *Site) MethodNotAllowed(fn any)

func (*Site) NotFound

func (site *Site) NotFound(fn any)

func (*Site) Options

func (site *Site) Options(pattern string, fn any, operations ...api.Operation) RouterOperation

func (*Site) Patch

func (site *Site) Patch(pattern string, fn any, operations ...api.Operation) RouterOperation

func (*Site) Post

func (site *Site) Post(pattern string, fn any, operations ...api.Operation) RouterOperation

func (*Site) PrintPaths

func (site *Site) PrintPaths()

func (*Site) Put

func (site *Site) Put(pattern string, fn any, operations ...api.Operation) RouterOperation

func (*Site) Route

func (site *Site) Route(pattern string, fn func(r Router)) Router

Route mounts a sub-Router along a `pattern“ string.

func (*Site) Run

func (site *Site) Run()

func (*Site) Send

func (site *Site) Send(response any, w http.ResponseWriter) error

Sends the response to the writer.

func (*Site) SendAny

func (site *Site) SendAny(response []byte, w http.ResponseWriter, status int, contentType api.ContentType)

func (*Site) ServeOpenJSON

func (site *Site) ServeOpenJSON(pattern string)

func (*Site) ServeRedoc

func (site *Site) ServeRedoc(pattern string)

func (*Site) ServeSwaggerUI

func (site *Site) ServeSwaggerUI(pattern string, options map[string]any)

func (*Site) SetErrorHandler

func (site *Site) SetErrorHandler(handler ErrorHandler)

Sets the error handler at this router and all sub routers created after this is set.

func (*Site) SetInternalErrorHandler

func (site *Site) SetInternalErrorHandler(handle InternalErrorHandler)

Sets the handler for errors we received outside of responding to the client.

func (*Site) SetOperations

func (site *Site) SetOperations(op api.Operation)

Sets the base operation. All sub routes will inherit the properties on the base operation.

func (*Site) SetResponses

func (site *Site) SetResponses(responses api.Responses)

Sets the tags for all child routes starting at this router

func (*Site) SetTags

func (site *Site) SetTags(tags []string)

Sets the tags for all child routes starting at this router

func (*Site) SetValidationOptions

func (site *Site) SetValidationOptions(valueOrType any, options ValidationOptions)

Sets the validation options for the type or value's type.

func (*Site) Trace

func (site *Site) Trace(pattern string, fn any, operations ...api.Operation) RouterOperation

func (Site) URL

func (site Site) URL() string

The url of the router at this point.

func (*Site) UpdateOperations

func (site *Site) UpdateOperations(op api.Operation)

Updates the base operation (merges in given properties into existing base operation). All sub routes will inherit the properties on the base operation.

func (*Site) UpdatePath

func (site *Site) UpdatePath(pattern string, path api.Path)

Gets the path defined at the given pattern, if any

func (*Site) Use

func (site *Site) Use(fns ...any)

Use appends one or more middlewares onto the Router stack.

func (Site) ValidationOptions

func (site Site) ValidationOptions(typ reflect.Type) ValidationOptions

Returns the validation options specified for the given type.

func (*Site) With

func (site *Site) With(fns ...any) Router

Use appends one or more middlewares onto the Router stack.

type SiteOperation added in v0.2.0

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

An operation for a site.

func (SiteOperation) Input added in v0.2.0

func (op SiteOperation) Input(input ...any)

func (SiteOperation) Operation added in v0.2.0

func (op SiteOperation) Operation() *api.Operation

func (SiteOperation) Output added in v0.2.0

func (op SiteOperation) Output(output ...any)

func (SiteOperation) Router added in v0.2.0

func (op SiteOperation) Router() Router

type TooManyRequests

type TooManyRequests[V any] struct {
	Result V
}

A 429 response.

func NewTooManyRequests

func NewTooManyRequests[V any](result V) *TooManyRequests[V]

func (TooManyRequests[V]) APIName added in v0.3.4

func (err TooManyRequests[V]) APIName() string

func (TooManyRequests[V]) APISchemaType added in v0.3.4

func (err TooManyRequests[V]) APISchemaType() any

func (TooManyRequests[V]) Error

func (err TooManyRequests[V]) Error() string

func (TooManyRequests[V]) HTTPStatus

func (err TooManyRequests[V]) HTTPStatus() int

func (TooManyRequests[V]) HTTPStatuses

func (err TooManyRequests[V]) HTTPStatuses() []int

func (TooManyRequests[V]) MarshalJSON

func (err TooManyRequests[V]) MarshalJSON() ([]byte, error)

func (*TooManyRequests[V]) UnmarshalJSON

func (err *TooManyRequests[V]) UnmarshalJSON(data []byte) error

type Unauthorized

type Unauthorized[V any] struct {
	Result V
}

A 401 response.

func NewUnauthorized

func NewUnauthorized[V any](result V) *Unauthorized[V]

func (Unauthorized[V]) APIName added in v0.3.4

func (err Unauthorized[V]) APIName() string

func (Unauthorized[V]) APISchemaType added in v0.3.4

func (err Unauthorized[V]) APISchemaType() any

func (Unauthorized[V]) Error

func (err Unauthorized[V]) Error() string

func (Unauthorized[V]) HTTPStatus

func (err Unauthorized[V]) HTTPStatus() int

func (Unauthorized[V]) HTTPStatuses

func (err Unauthorized[V]) HTTPStatuses() []int

func (Unauthorized[V]) MarshalJSON

func (err Unauthorized[V]) MarshalJSON() ([]byte, error)

func (*Unauthorized[V]) UnmarshalJSON

func (err *Unauthorized[V]) UnmarshalJSON(data []byte) error

type Validation

type Validation struct {
	// The path to the offending value.
	Path []string `json:"path,omitempty"`
	// The name of the schema, if any.
	Schema *string `json:"schema,omitempty"`
	// The validation rule that caused the failure.
	Rule ValidationRule `json:"rule,omitempty"`
	// A message with more details.
	Message string `json:"message,omitempty"`
}

A validation failure

type ValidationOptions

type ValidationOptions struct {
	// If all validation should be skipped.
	Skip bool
	// If format is set, if the string representation of the
	// value should be validated against the specified format (if its supported).
	EnforceFormat bool
	// If specifying a deprecated value should result in a validation error.
	FailDeprecated bool
	// If validation should be skipped for deprecated schemas
	SkipDeprecated bool
}

Options for validating a particular type.

type ValidationProvider

type ValidationProvider interface {
	ValidationOptions(reflect.Type) ValidationOptions
}

An interface which helps the validation process.

type ValidationRule

type ValidationRule string

A rule that was broken that caused the validation failure.

const (
	ValidationRuleType          ValidationRule = "type"
	ValidationRuleMultipleOf    ValidationRule = "multipleOf"
	ValidationRuleMaximum       ValidationRule = "maximum"
	ValidationRuleMinimum       ValidationRule = "minimum"
	ValidationRuleMaxLength     ValidationRule = "maxLength"
	ValidationRuleMinLength     ValidationRule = "minLength"
	ValidationRulePattern       ValidationRule = "pattern"
	ValidationRuleFormat        ValidationRule = "format"
	ValidationRuleMaxItems      ValidationRule = "maxItems"
	ValidationRuleMinItems      ValidationRule = "minItems"
	ValidationRuleUniqueItems   ValidationRule = "uniqueItems"
	ValidationRuleMaxProperties ValidationRule = "maxProperties"
	ValidationRuleMinProperties ValidationRule = "minProperties"
	ValidationRuleRequired      ValidationRule = "required"
	ValidationRuleDeprecated    ValidationRule = "deprecated"
	ValidationRuleEnum          ValidationRule = "enum"
	ValidationRuleNullable      ValidationRule = "nullable"
	ValidationRuleOneOf         ValidationRule = "oneOf"
	ValidationRuleAllOf         ValidationRule = "allOf"
	ValidationRuleAnyOf         ValidationRule = "anyOf"
	ValidationRuleNot           ValidationRule = "not"
	ValidationRuleCustom        ValidationRule = "custom"
)

type Validator

type Validator struct {
	Path        []string           `json:"-"`
	Validations *[]Validation      `json:"validations"`
	Provider    ValidationProvider `json:"-"`
	Scope       *deps.Scope        `json:"-"`
}

A validator for a specific element being validated. Validators all share Validations and Providers. Adding a validation to one adds it to the others.

func NewValidator

func NewValidator(provider ValidationProvider, scope *deps.Scope) *Validator

Creates a new validator for the given provider and scope.

func (*Validator) Add

func (v *Validator) Add(msg Validation)

Adds a validation error to the validator. If no path is specified on the validation then the path of the validator is applied.

func (*Validator) Attach

func (v *Validator) Attach(detached Validator)

Attaches a validtor to this validator by adding its validations to this one.

func (Validator) Detach

func (v Validator) Detach() Validator

Creates a validator with the same path but does not share validations.

func (Validator) Error

func (v Validator) Error() string

Validator implements error

func (Validator) HTTPStatus

func (v Validator) HTTPStatus() int

400 is used, this also signals to return the error as JSON.

func (Validator) HTTPStatuses

func (v Validator) HTTPStatuses() []int

func (Validator) HasFailures

func (v Validator) HasFailures() bool

Returns true if the validator has failures.

func (Validator) IsValid

func (v Validator) IsValid() bool

Returns true if the validator has no failures.

func (Validator) Next

func (v Validator) Next(path string) *Validator

Returns a child validator with the added path node. Validations are shared.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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