router

package
v0.2.14 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2022 License: Apache-2.0 Imports: 42 Imported by: 0

README

Resource

Router provides REST Api layer. Internally it uses the Views in order to communicate with database and add extra layer to handle http requests in order to read and filter data. It can be configured programmatically or by reading external configuration from yaml file.

In the yaml file, following sections can be configured:

Section Description Type Required
Routes configuration for specific route []Route true
Resource configuration of Views, Connectors and Parameters shared across the Routes Resource false
Compression Compression configuraion that will be used for all Routes unless Route Compression is configured Compression false
Cors Cors configuraion that will be used for all Routes unless Route Cors is configured Cors false
APIURI string true
SourceURL string false
With []string false

Cors

In order to enable the web browser cross-origin requests, the Cors need to be configured. If any of the section is not specified, corresponding Http header will not be added to the Cors preflight request:

Section Description Type Required
AllowCredentials Access-Control-Allow-Credentials header value bool false
AllowHeaders Access-Control-Allow-Headers header value []string false
AllowMethods Access-Control-Allow-Methods header value []string false
AllowOrigins Access-Control-Allow-Origin header value []string false
ExposeHeaders Access-Control-Expose-Headers header value []string false
MaxAge Access-Control-Max-Age header value int false

Compression

In order to compress data if response exceed given size, Compression configuration need to be specified:

Section Description Type Required Default value
MinSizeKb Minimum size in KB after when response should be compressed int false 0

Route

Route configures specific URL handler for given http method. The Compression and Cors can be configured on the router level, but can also be overridden on the Route level. In the Route section, following properties can be configured.

Section Description Type Required Default value
URI Url pattern that Requests will be matched with. The path variables have to be put between brackets i.e. /users/{userId} string true ""
View View definition used to fetch data from database View true null
Method Http method used to match http requests enum: GET, POST true ""
Service The service type used to handle the requests. enum: Reader false GET -> Reader, Post -> ""
Cors Cors configuration specific for the Route Cors false null
Cardinality Indicates whether single object should be returned or the array of objects. enum: ONE, MANY false MANY
CaseFormat Configures the output JSON field names format. enum: CaseFormat false uppercamel
OmitEmpty Removes zero values from the output. Examples of removable values: 0, "", false, [], null boolean false false
Style Indicates whether response body should be wrapped with status code and error message (Comprehensive) or just returned as is enum: Basic, Comprehensive false Basic
ResponseField ResponseBody field for Comprehensive Style string in the UperCamelCase format false ResponseBody
Namespace Mapping between Selector prefix into the View name string -> string map / pairs false null
Visitor Interceptor that can execute some logic before or/and after data was fetched from database. In order to use Visitors, Visitor need to be created programmatically and passed to the Configuration Visitor false null
View View configuration used to fetch data from database View true null
Compression Route specific Compression configuration Compression false null
Cache Route specific Cache configuration Cache false null
Exclude Fields that will be excluded from response. Field paths in format: CammelCase.CammelCase.OutputCase, i.e. - Employees.Departments.id false []string{}
NormalizeExclude In order to use Excluded path using only CammelCase NormalizeExclude needs to be set to false. bool false true

Cache

Cache caches the database result for the main view specified on the Route level. It uses the Selectors to produce entry key. The cache key is produced using the Selectors. If two http requests produces the same Selectors, and one happen after the other in time shorter than specified, the data will be read from the cache:

Section Description Type Required
TimeToLiveMs Cache entry time after when entry will be invalidated int true
StorageURL URL of the stored cache entries string true

Visitor

Visitor intercepts regular reader flow. Visitor executes regular golang code so in order to use them they have to be registered before Resource is initialized. It can implement following interfaces:

  • BeforeFetch - executes before data is fetched from the database.
BeforeFetch(response http.ResponseWriter, request *http.Request) (responseClosed bool, err error)
  • AfterFetch - executes after data is fetched from the database.
AfterFetch(data interface{}, response http.ResponseWriter, request *http.Request) (responseClosed bool, err error)
Section Description Type Required
Name Visitor name, has to match visitors map key provided programmatically string true

Examples

For examples see test cases

Documentation

Index

Constants

View Source
const (
	//ContentTypeJSON json content type
	ContentTypeJSON = "application/json"

	CharsetUTF8 = "charset=utf-8"
	//EncodingGzip encoding gzip
	EncodingGzip = "gzip"

	ContentLength = "Content-Length"
)
View Source
const (
	BasicStyle         Style = "Basic"
	ComprehensiveStyle Style = "Comprehensive"

	ReaderServiceType   ServiceType = "Reader"
	ExecutorServiceType ServiceType = "Executor"
)
View Source
const (
	AllowOriginHeader      = "Access-Control-Allow-Origin"
	AllowHeadersHeader     = "Access-Control-Allow-Headers"
	AllowMethodsHeader     = "Access-Control-Allow-Methods"
	AllowCredentialsHeader = "Access-Control-Allow-Credentials"
	ExposeHeadersHeader    = "Access-Control-Expose-Headers"
	MaxAgeHeader           = "Access-Control-Max-Age"
	Separator              = ", "
)
View Source
const (
	ValuesSeparator = ','
)

Variables

This section is empty.

Functions

func Compress

func Compress(reader io.Reader) (*bytes.Buffer, error)

Compress compresses input using gzip

func CreateSelectors

func CreateSelectors(ctx context.Context, dateFormat string, inputFormat format.Case, requestMetadata *RequestMetadata, requestParams *RequestParams, views ...*ViewDetails) (*view.Selectors, error)

func CreateSelectorsFromRoute

func CreateSelectorsFromRoute(ctx context.Context, route *Route, request *http.Request, views ...*ViewDetails) (*view.Selectors, error)

func FieldByName added in v0.2.11

func FieldByName(responseType reflect.Type, name string) *xunsafe.Field

func GenerateGoStruct added in v0.2.4

func GenerateGoStruct(name string, structType reflect.Type) string

func GenerateOpenAPI3Spec added in v0.2.1

func GenerateOpenAPI3Spec(info openapi3.Info, routes ...*Route) (*openapi3.OpenAPI, error)

Types

type APIKey added in v0.2.11

type APIKey struct {
	URI    string
	Value  string
	Header string
}

type APIKeys added in v0.2.11

type APIKeys []*APIKey

func (APIKeys) Len added in v0.2.11

func (a APIKeys) Len() int

func (APIKeys) Less added in v0.2.11

func (a APIKeys) Less(i, j int) bool

func (APIKeys) Match added in v0.2.11

func (a APIKeys) Match(URI string) *APIKey

func (APIKeys) Swap added in v0.2.11

func (a APIKeys) Swap(i, j int)

type ApiPrefix added in v0.2.7

type ApiPrefix string

type Audit added in v0.2.3

type Audit struct {
	URL     string
	Headers map[string][]string
}

type BytesReadCloser added in v0.2.2

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

func (*BytesReadCloser) Close added in v0.2.2

func (b *BytesReadCloser) Close() error

func (*BytesReadCloser) Read added in v0.2.2

func (b *BytesReadCloser) Read(p []byte) (int, error)

type Compression

type Compression struct {
	MinSizeKb int
}

type Cors

type Cors struct {
	AllowCredentials *bool
	AllowHeaders     *[]string
	AllowMethods     *[]string
	AllowOrigins     *[]string
	ExposeHeaders    *[]string
	MaxAge           *int64
}

type Error added in v0.2.1

type Error struct {
	View    string      `json:",omitempty" default:"nullable=true,required=false,allowEmpty=true"`
	Param   string      `json:",omitempty" default:"nullable=true,required=false,allowEmpty=true"`
	Err     error       `json:"-"`
	Message string      `json:",omitempty" default:"nullable=true,required=false,allowEmpty=true"`
	Object  interface{} `json:",omitempty" default:"nullable=true,required=false,allowEmpty=true"`
}

func (*Error) Error added in v0.2.1

func (e *Error) Error() string

type Errors added in v0.2.1

type Errors struct {
	Errors []*Error
	// contains filtered or unexported fields
}

func NewErrors added in v0.2.1

func NewErrors() *Errors

func (*Errors) AddError added in v0.2.1

func (e *Errors) AddError(view, param string, err error)

func (*Errors) Error added in v0.2.1

func (e *Errors) Error() string

type Index

type Index struct {
	Namespace map[string]string
	// contains filtered or unexported fields
}

func (*Index) Init

func (i *Index) Init(aView *view.View, path string) error

func (*Index) ViewByPrefix

func (i *Index) ViewByPrefix(prefix string) (*view.View, error)

func (*Index) ViewNamespace added in v0.2.2

func (i *Index) ViewNamespace(aView *view.View) string

type JSONError added in v0.2.11

type JSONError struct {
	Object interface{}
}

func (*JSONError) Error added in v0.2.11

func (e *JSONError) Error() string

func (*JSONError) MarshalJSON added in v0.2.11

func (e *JSONError) MarshalJSON() ([]byte, error)

type Logger

type Logger struct {
	MinExecutionMs *int
}

type Matcher added in v0.2.7

type Matcher struct {
	Nodes  []*Node
	Routes []*Route
	// contains filtered or unexported fields
}

func NewMatcher added in v0.2.7

func NewMatcher(routes []*Route) *Matcher

func (*Matcher) Match added in v0.2.7

func (m *Matcher) Match(method, route string) (*Route, error)

type Node added in v0.2.7

type Node struct {
	Matched         []int
	ExactChildren   []*Node
	WildcardMatcher *Node
	// contains filtered or unexported fields
}

func NewNode added in v0.2.7

func NewNode() *Node

func (*Node) Add added in v0.2.7

func (n *Node) Add(routeIndex int, uri string)

func (*Node) Match added in v0.2.7

func (n *Node) Match(method, route string) (*Node, bool)

type NodeMatch added in v0.2.7

type NodeMatch struct {
	URL  string
	Node *Node
}

type Output

type Output struct {
	Cardinality      view.Cardinality `json:",omitempty"`
	CaseFormat       view.CaseFormat  `json:",omitempty"`
	OmitEmpty        bool             `json:",omitempty"`
	Style            Style            `json:",omitempty"`
	ResponseField    string           `json:",omitempty"`
	Transforms       marshal.Transforms
	Exclude          []string
	NormalizeExclude *bool
	DateFormat       string `json:",omitempty"`
	// contains filtered or unexported fields
}

type Param

type Param struct {
	Value string
}

type ParamError added in v0.2.1

type ParamError struct {
	Value interface{}
	Field string
	Tag   string
}

type ParamErrors added in v0.2.1

type ParamErrors []*ParamError

func NewParamErrors added in v0.2.1

func NewParamErrors(validationErrors validator.ValidationErrors) ParamErrors

func (ParamErrors) Error added in v0.2.1

func (p ParamErrors) Error() string

type PayloadReader added in v0.2.2

type PayloadReader interface {
	io.Reader
	Size() int
	CompressionType() string
	Close() error
	Headers() http.Header
}

type QueryParam

type QueryParam string
const (
	Fields   QueryParam = "_fields"
	Offset   QueryParam = "_offset"
	OrderBy  QueryParam = "_orderby"
	Limit    QueryParam = "_limit"
	Criteria QueryParam = "_criteria"
	Page     QueryParam = "_page"
)

func (QueryParam) Description added in v0.2.1

func (q QueryParam) Description(viewName string) string

func (QueryParam) ParamType added in v0.2.1

func (q QueryParam) ParamType() reflect.Type

type Redirect

type Redirect struct {
	StorageURL   string ///github.com/viant/datly/v0/app/lambda/lambda/proxy.go
	MinSizeKb    int
	TimeToLiveMs int
}

func (*Redirect) Apply added in v0.2.1

func (r *Redirect) Apply(ctx context.Context, viewName string, payload PayloadReader) (*option.PreSign, error)

func (*Redirect) TimeToLive added in v0.2.1

func (r *Redirect) TimeToLive() time.Duration

type RequestDataReader added in v0.2.11

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

func AsBytesReader added in v0.2.2

func AsBytesReader(buffer *bytes.Buffer, compression string, size int) *RequestDataReader

func NewBytesReader added in v0.2.2

func NewBytesReader(data []byte, compression string) *RequestDataReader

func (*RequestDataReader) AddHeader added in v0.2.11

func (b *RequestDataReader) AddHeader(name string, value string)

func (*RequestDataReader) Close added in v0.2.11

func (b *RequestDataReader) Close() error

func (*RequestDataReader) CompressionType added in v0.2.11

func (b *RequestDataReader) CompressionType() string

func (*RequestDataReader) Headers added in v0.2.11

func (b *RequestDataReader) Headers() http.Header

func (*RequestDataReader) Read added in v0.2.11

func (b *RequestDataReader) Read(p []byte) (n int, err error)

func (*RequestDataReader) Size added in v0.2.11

func (b *RequestDataReader) Size() int

type RequestMetadata

type RequestMetadata struct {
	URI      string
	Index    Index
	MainView *view.View
}

func NewRequestMetadata

func NewRequestMetadata(route *Route) *RequestMetadata

type RequestParams

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

func NewRequestParameters

func NewRequestParameters(request *http.Request, route *Route) (*RequestParams, error)

type Resource

type Resource struct {
	APIURI       string
	MetaCacheURI string
	SourceURL    string
	With         []string //list of resource to inherit from
	Routes       Routes
	Resource     *view.Resource
	Compression  *Compression
	Redirect     *Redirect
	Cache        *cache.Cache
	Logger       *Logger //connect, dataview, time, SQL with params if exceeded time
	Cors         *Cors

	ColumnsCache     *discover.Cache
	ParamStatusError *int

	Info openapi3.Info

	ColumnsDiscovery bool
	// contains filtered or unexported fields
}

func NewResourceFromURL

func NewResourceFromURL(ctx context.Context, fs afs.Service, URL string, useColumnCache bool, options ...interface{}) (*Resource, error)

func (*Resource) Init

func (r *Resource) Init(ctx context.Context) error

type ResponseStatus

type ResponseStatus struct {
	Status  string      `json:",omitempty"`
	Message interface{} `json:",omitempty"`
}

type Route

type Route struct {
	Visitor     *codec.Visitor
	URI         string
	APIKey      *APIKey
	Method      string
	Service     ServiceType
	View        *view.View
	Cors        *Cors
	EnableAudit bool
	Output
	Index

	ParamStatusError *int
	Cache            *cache.Cache
	Compression      *Compression
	// contains filtered or unexported fields
}

func (*Route) Init

func (r *Route) Init(ctx context.Context, resource *Resource) error

func (*Route) PgkPath added in v0.2.11

func (r *Route) PgkPath(fieldName string) string

func (*Route) PrefixByView added in v0.2.1

func (r *Route) PrefixByView(aView *view.View) (string, bool)

func (*Route) ShouldNormalizeExclude added in v0.2.1

func (r *Route) ShouldNormalizeExclude() bool

type Router

type Router struct {
	Matcher *Matcher
	// contains filtered or unexported fields
}

func New

func New(resource *Resource, options ...interface{}) *Router

func (*Router) ApiPrefix added in v0.2.1

func (r *Router) ApiPrefix() string

func (*Router) Handle

func (r *Router) Handle(response http.ResponseWriter, request *http.Request) error

func (*Router) Init

func (r *Router) Init(routes Routes, apiPrefix string)

func (*Router) Routes added in v0.2.2

func (r *Router) Routes(route string) []*Route

func (*Router) Serve

func (r *Router) Serve(serverPath string) error

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(writer http.ResponseWriter, request *http.Request)

func (*Router) View

func (r *Router) View(name string) (*view.View, error)

type Routes

type Routes []*Route

type SelectorParamIt

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

func NewParamIt

func NewParamIt(value string, separators ...int32) *SelectorParamIt

func (*SelectorParamIt) Has

func (s *SelectorParamIt) Has() bool

func (*SelectorParamIt) Next

func (s *SelectorParamIt) Next() (Param, error)

type ServiceType

type ServiceType string

type Style

type Style string

type ViewDetails

type ViewDetails struct {
	View     *view.View
	Path     string
	Prefixes []string
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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