router

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: May 25, 2022 License: Apache-2.0 Imports: 29 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

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 (
	BasicStyle         Style = "Basic"
	ComprehensiveStyle Style = "Comprehensive"

	ReaderServiceType ServiceType = "Reader"
)
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, 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)

Types

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 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)

type Loader

type Loader struct {
	Ctx  context.Context
	Path string
	// contains filtered or unexported fields
}

func NewLoader

func NewLoader(ctx context.Context, path string) *Loader

func (*Loader) Load

func (l *Loader) Load() (*Resource, error)

func (*Loader) SetAfsService

func (l *Loader) SetAfsService(service afs.Service) *Loader

func (*Loader) SetDependencies

func (l *Loader) SetDependencies(dependencies map[string]*view.Resource) *Loader

func (*Loader) SetMetrics

func (l *Loader) SetMetrics(metrics *view.Metrics) *Loader

func (*Loader) SetTypes

func (l *Loader) SetTypes(types view.Types) *Loader

func (*Loader) SetVisitors

func (l *Loader) SetVisitors(visitors visitor.Visitors) *Loader

type Logger

type Logger struct {
	MinExecutionMs int
}

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"`
	// contains filtered or unexported fields
}

type Param

type Param struct {
	Value string
}

type QueryParam

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

type Redirect

type Redirect struct {
	StorageURL string ///github.com/viant/datly/v0/app/lambda/lambda/proxy.go
	MinSizeKb  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
	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   //TODO github.com/viant/datly/v0/app/lambda/bridge/cors.go
	// contains filtered or unexported fields
}

func NewResourceFromURL

func NewResourceFromURL(ctx context.Context, fs afs.Service, URL string, visitors visitor.Visitors, types view.Types, resources map[string]*view.Resource, metrics *view.Metrics) (*Resource, error)

func (*Resource) Init

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

type ResponseStatus

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

type Route

type Route struct {
	Visitor *visitor.Visitor
	URI     string
	Method  string
	Service ServiceType
	View    *view.View
	Cors    *Cors
	Output
	Index

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

func (*Route) Init

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

type Router

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

func New

func New(resource *Resource) *Router

func (*Router) Handle

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

func (*Router) Init

func (r *Router) Init(routes Routes)

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) *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 UnspecifiedPrefix

type UnspecifiedPrefix struct {
	Prefix string
}

func NewUnspecifiedPrefix

func NewUnspecifiedPrefix(prefix string) *UnspecifiedPrefix

func (*UnspecifiedPrefix) Error

func (u *UnspecifiedPrefix) Error() string

type UnsupportedFormat

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

func NewUnsupportedFormat

func NewUnsupportedFormat(paramName, paramValue string) *UnsupportedFormat

func (*UnsupportedFormat) Error

func (u *UnsupportedFormat) Error() string

type ViewDetails

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

Directories

Path Synopsis
sql

Jump to

Keyboard shortcuts

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