definition

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Jan 21, 2021 License: Apache-2.0 Imports: 3 Imported by: 226

Documentation

Index

Constants

View Source
const (
	// MIMEAll indicates a accept type from http request.
	// It means client can receive any content.
	// Request content type in header "Content-Type" must not set to "*/*".
	// It only can exist in request header "Accept".
	// In most time, it locate at the last element of "Accept".
	// It's default value if client have not set "Accept" header.
	MIMEAll         = "*/*"
	MIMENone        = ""
	MIMEText        = "text/plain"
	MIMEHTML        = "text/html"
	MIMEJSON        = "application/json"
	MIMEXML         = "application/xml"
	MIMEOctetStream = "application/octet-stream"
	MIMEURLEncoded  = "application/x-www-form-urlencoded"
	MIMEFormData    = "multipart/form-data"
)

MIME types

Variables

This section is empty.

Functions

This section is empty.

Types

type Chain

type Chain interface {
	// Continue continues to execute the next subsequent actions.
	Continue(context.Context) error
}

Chain contains all subsequent actions.

type Definition

type Definition struct {
	// Method is definition method.
	Method Method
	// Consumes indicates how many content types the handler can consume.
	// It will override parent descriptor's consumes.
	Consumes []string
	// Produces indicates how many content types the handler can produce.
	// It will override parent descriptor's produces.
	Produces []string
	// Tags indicates tags of the API handler.
	// It will override parent descriptor's tags.
	Tags []string
	// ErrorProduces is used to generate data for error. If this field is empty,
	// it means that this field equals to Produces.
	// In some cases, successful data and error data should be generated in
	// different ways.
	ErrorProduces []string
	// Function is a function handler. It must be func type.
	Function interface{}
	// Parameters describes function parameters.
	Parameters []Parameter
	// Results describes function return values.
	Results []Result
	// Summary is a one-line brief description of this definition.
	Summary string
	// Description describes the API handler.
	Description string
	// Examples contains many examples for the API handler.
	Examples []Example
}

Definition defines an API handler.

type Descriptor

type Descriptor struct {
	// Path is the url path. It will inherit parent's path.
	//
	// If parent path is "/api/v1", current is "/some",
	// It means current definitions handles "/api/v1/some".
	Path string
	// Consumes indicates content types that current definitions
	// and child definitions can consume.
	// It will override parent descriptor's consumes.
	Consumes []string
	// Produces indicates content types that current definitions
	// and child definitions can produce.
	// It will override parent descriptor's produces.
	Produces []string
	// Tags indicates tags of current definitions and child definitions.
	// It will override parent descriptor's tags.
	Tags []string
	// Middlewares contains path middlewares.
	Middlewares []Middleware
	// Definitions contains definitions for current path.
	Definitions []Definition
	// Children is used to place sub-descriptors.
	Children []Descriptor
	// Description describes the usage of the path.
	Description string
}

Descriptor describes a descriptor for API definitions.

func SimpleDescriptor

func SimpleDescriptor(method Method, path string, f interface{}) Descriptor

SimpleDescriptor creates a simple REST descriptor for handler. The descriptor consumes all content types and produces all accept types.

type Destination

type Destination string

Destination indicates the target type to place function results.

const (
	// Meta means result will be set into the header of response.
	Meta Destination = "Meta"
	// Data means result will be set into the body of response.
	Data Destination = "Data"
	// Error means the result is an error and should be treated specially.
	// An error occurs indicates that there is no data to return. So the
	// error should be treated as data and be writed back to client.
	Error Destination = "Error"
)

type Example

type Example struct {
	// Description describes the example.
	Description string
	// Instance is a custom data.
	Instance interface{}
}

Example is just an example.

type Method

type Method string

Method is an alternative of HTTP method. It's more clearer than HTTP method. A definition method binds a certain HTTP method and a success status code.

const (
	// Any used to register all methods for a Definition.
	Any Method = "Any"
	// Head binds to http.MethodHead and code http.StatusOK(200).
	Head Method = "Head"
	// List binds to http.MethodGet and code http.StatusOK(200).
	List Method = "List"
	// Get binds to http.MethodGet and code http.StatusOK(200).
	Get Method = "Get"
	// Create binds to http.MethodPost and code http.StatusCreated(201).
	Create Method = "Create"
	// Update binds to http.MethodPut and code http.StatusOK(200).
	Update Method = "Update"
	// Patch binds to http.MethodPatch and code http.StatusOK(200).
	Patch Method = "Patch"
	// Delete binds to http.MethodDelete and code http.StatusNoContent(204).
	Delete Method = "Delete"
	// AsyncCreate binds to http.MethodPost and code http.StatusAccepted(202).
	AsyncCreate Method = "AsyncCreate"
	// AsyncUpdate binds to http.MethodPut and code http.StatusAccepted(202).
	AsyncUpdate Method = "AsyncUpdate"
	// AsyncPatch binds to http.MethodPatch and code http.StatusAccepted(202).
	AsyncPatch Method = "AsyncPatch"
	// AsyncDelete binds to http.MethodDelete and code http.StatusAccepted(202).
	AsyncDelete Method = "AsyncDelete"
)

type Middleware

type Middleware func(context.Context, Chain) error

Middleware describes the form of middlewares. If you want to carry on, call Chain.Continue() and pass the context.

type Operator

type Operator interface {
	// Kind indicates operator type.
	Kind() string
	// In returns the type of the only object parameter of operator.
	// The type must be a concrete struct or built-in type. It should
	// not be interface unless it's a file or stream reader.
	In() reflect.Type
	// Out returns the type of the only object result of operator.
	// The type must be a concrete struct or built-in type. It should
	// not be interface unless it's a file or stream reader.
	Out() reflect.Type
	// Operate operates an object and return one.
	Operate(ctx context.Context, field string, object interface{}) (interface{}, error)
}

Operator is used to operate an object and return an replacement object.

For example:

A converter:
  type ConverterForAnObject struct{}
  func (c *ConverterForAnObject) Kind() {return "converter"}
  func (c *ConverterForAnObject) In() reflect.Type {return definition.TypeOf(&ObjectV1{})}
  func (c *ConverterForAnObject) Out() reflect.Type {return definition.TypeOf(&ObjectV2{})}
  func (c *ConverterForAnObject) Operate(ctx context.Context, object interface{}) (interface{}, error) {
      objV2, err := convertObjectV1ToObjectV2(object.(*ObjectV1))
      return objV2, err
  }

A validator:
  type ValidatorForAnObject struct{}
  func (c *ValidatorForAnObject) Kind() {return "validator"}
  func (c *ValidatorForAnObject) In() reflect.Type {return definition.TypeOf(&Object{})}
  func (c *ValidatorForAnObject) Out() reflect.Type {return definition.TypeOf(&Object{})}
  func (c *ValidatorForAnObject) Operate(ctx context.Context, object interface{}) (interface{}, error) {
      if err := validate(object.(*Object)); err != nil {
          return nil, err
      }
      return object, nil
  }

func NewOperator

func NewOperator(kind string, in, out reflect.Type, f func(ctx context.Context, field string, object interface{}) (interface{}, error)) Operator

NewOperator creates operator by function. function must has signature:

func f(context.Context, AnyType) (AnyType, error)

AnyType can be any type in go. But struct type and built-in data type is recommended.

func OperatorFunc

func OperatorFunc(kind string, f interface{}) Operator

OperatorFunc creates operator by function. function must has signature:

func f(context.Context, string, AnyType) (AnyType, error)

The second parameter is a string that is used to identify field. AnyType can be any type in go. But struct type and built-in data type is recommended.

type Parameter

type Parameter struct {
	// Source is the parameter value generated from.
	Source Source
	// Name is the name to get value from a request.
	// ex. a query name, a header key, etc.
	Name string
	// Default value is used when a request does not provide a value
	// for the parameter.
	Default interface{}
	// Operators can modify and validate the target value.
	// Parameter value is passed to the first operator, then
	// previous operator's result is as next operator's parameter.
	// The result of last operator will be passed to target function.
	Operators []Operator
	// Description describes the parameter.
	Description string
	// Optional used to set whether this parameter is optional or not, we take the File parameter as an example,
	// in current usage, if the value of parameter is empty, nirvana will return an error directly:
	// {
	//    "reason": "Nirvana:Service:RequiredField",
	//    "message": "required field file in File but got empty",
	//    "data": {
	//        "field": "file",
	//        "source": "File"
	//    }
	// }
	//
	// if you set the `Optional` to true, then nirvana won't interrupt the request, you can handle
	// the situation where the parameter may be nil yourself, eg:
	//
	// func Upload(ctx context.Context, file multipart.File) (string, error) {
	//    if file == nil {
	//        // do something
	//    }
	//    // do something else
	// }
	Optional bool
}

Parameter describes a function parameter.

func AutoParameterFor

func AutoParameterFor(description string, operators ...Operator) Parameter

AutoParameterFor creates an auto parameter

func BodyParameterFor

func BodyParameterFor(description string, operators ...Operator) Parameter

BodyParameterFor creates a body parameter

func FileParameterFor

func FileParameterFor(name string, description string, operators ...Operator) Parameter

FileParameterFor creates a file parameter

func FormParameterFor

func FormParameterFor(name string, description string, operators ...Operator) Parameter

FormParameterFor creates a form parameter

func HeaderParameterFor

func HeaderParameterFor(name string, description string, operators ...Operator) Parameter

HeaderParameterFor creates a header parameter

func ParameterFor

func ParameterFor(source Source, name string, description string, operators ...Operator) Parameter

ParameterFor creates a simple parameter.

func PathParameterFor

func PathParameterFor(name string, description string, operators ...Operator) Parameter

PathParameterFor creates a path parameter

func PrefabParameterFor

func PrefabParameterFor(name string, description string, operators ...Operator) Parameter

PrefabParameterFor creates a prefab parameter

func QueryParameterFor

func QueryParameterFor(name string, description string, operators ...Operator) Parameter

QueryParameterFor creates a query parameter

type RPCAction added in v0.3.0

type RPCAction struct {
	// Version defines the version this API belongs to.
	// Need to use time format, eg: 2020-10-10
	Version string
	// Name defines the Action name.
	Name string
	// Consumes indicates how many content types the handler can consume.
	// It will override parent descriptor's consumes.
	Consumes []string
	// Produces indicates how many content types the handler can produce.
	// It will override parent descriptor's produces.
	Produces []string
	// Tags indicates tags of the API handler.
	// It will override parent descriptor's tags.
	Tags []string
	// ErrorProduces is used to generate data for error. If this field is empty,
	// it means that this field equals to Produces.
	// In some cases, succeessful data and error data should be generated in
	// different ways.
	ErrorProduces []string
	// Function is a function handler. It must be func type.
	Function interface{}
	// Parameters describes function parameters.
	Parameters []Parameter
	// Results describes function retrun values.
	Results []Result
	// Description describes the API handler.
	Description string
	// Examples contains many examples for the API handler.
	Examples []Example
}

RPCAction defines an API handler in RPC style.

type RPCDescriptor added in v0.3.0

type RPCDescriptor struct {
	// Path describes url path prefix for all RPCActions, default: "/".
	Path string
	// Description describes the usage of the path.
	Description string
	// Middlewares contains path middlewares.
	Middlewares []Middleware
	// Tags indicates tags of current definitions and child definitions.
	// It will override parent descriptor's tags.
	Tags []string
	// Consumes indicates content types that current definitions
	// and child definitions can consume.
	// It will override parent descriptor's consumes.
	Consumes []string
	// Produces indicates content types that current definitions
	// and child definitions can produce.
	// It will override parent descriptor's produces.
	Produces []string
	// Actions contain actions in this descriptor. These actions will inherit the Middlewares, Tags, Consumes, Produces
	// of the descriptor if values in the action are not specified.
	Actions []RPCAction
}

RPCDescriptor describes a descriptor for API definition in RPC style.

func SimpleRPCDescriptor added in v0.3.0

func SimpleRPCDescriptor(path string, f interface{}) RPCDescriptor

SimpleRPCDescriptor creates a simple RPC descriptor for handler. The descriptor consumes all content types and produces all accept types.

type Result

type Result struct {
	// Destination is the target for the result. Different types make different behavior.
	Destination Destination
	// Operators can modify the result value.
	// Result value is passed to the first operator, then
	// previous operator's result is as next operator's parameter.
	// The result of last operator will be passed to destination handler.
	Operators []Operator
	// Description describes the result.
	Description string
}

Result describes how to handle a result from function results.

func DataErrorResults

func DataErrorResults(description string) []Result

DataErrorResults returns the most frequently-used results. Definition function should have two results. The first is any type for data, and the last is error.

func DataResultFor

func DataResultFor(description string, operators ...Operator) Result

DataResultFor creates data result.

func ErrorResult

func ErrorResult() Result

ErrorResult creates error result.

func MetaResultFor

func MetaResultFor(description string, operators ...Operator) Result

MetaResultFor creates meta result.

func ResultFor

func ResultFor(dest Destination, description string, operators ...Operator) Result

ResultFor creates a simple result.

type Source

type Source string

Source indicates which place a value is from.

const (
	// Path means value is from URL path.
	Path Source = "Path"
	// Query means value is from URL query string.
	Query Source = "Query"
	// Header means value is from request header.
	Header Source = "Header"
	// Form means value is from request body and content type must be
	// "application/x-www-form-urlencoded" and "multipart/form-data".
	Form Source = "Form"
	// File means value is from request body and content type must be
	// "multipart/form-data".
	File Source = "File"
	// Body means value is from request body.
	Body Source = "Body"
	// Auto identifies a struct and generate field values by field tag.
	//
	// Tag name is "source". Its value format is "Source,Name".
	//
	// ex.
	// type Example struct {
	//     Start       int    `source:"Query,start"`
	//     ContentType string `source:"Header,Content-Type"`
	// }
	Auto Source = "Auto"
	// Prefab means value is from a prefab generator.
	// A prefab combines data to generate value.
	Prefab Source = "Prefab"
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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