router

package
v0.9.5 Latest Latest
Warning

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

Go to latest
Published: Aug 16, 2024 License: Apache-2.0 Imports: 47 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
Field 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 (
	HeaderContentType = "Content-Type"
)
View Source
const (
	Separator = ", "
)

Variables

This section is empty.

Functions

func CorsHandler

func CorsHandler(request *http.Request, cors *path.Cors) func(writer http.ResponseWriter)

func ExtractCacheableViews

func ExtractCacheableViews(ctx context.Context, component *repository.Component) ([]*view.View, error)

func Sanitize

func Sanitize(request *http.Request, aPath *path.Path, headers http.Header, response http.ResponseWriter)

Types

type ContextHandler

type ContextHandler func(ctx context.Context, response http.ResponseWriter, request *http.Request)

ContextHandler http handler with context

type Handler

type Handler struct {
	Path     *path.Path
	Provider *repository.Provider
	// contains filtered or unexported fields
}

func New

func New(aPath *path.Path, provider *repository.Provider) *Handler

func (*Handler) AuthorizeRequest

func (r *Handler) AuthorizeRequest(request *http.Request, aPath *path.Path) error

func (*Handler) Handle

func (r *Handler) Handle(ctx context.Context, writer http.ResponseWriter, request *http.Request)

func (*Handler) HandleRequest

func (r *Handler) HandleRequest(ctx context.Context, response http.ResponseWriter, request *http.Request)

func (*Handler) PreSign

func (r *Handler) PreSign(ctx context.Context, viewName string, aResponse response.Response) (*option.PreSign, error)

func (*Handler) Serve

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

func (*Handler) ServeHTTP

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

type Httper

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

func (*Httper) FailWithCode

func (h *Httper) FailWithCode(statusCode int, err error) error

func (*Httper) RawRequest

func (h *Httper) RawRequest() *http.Request

func (*Httper) RequestOf

func (h *Httper) RequestOf(ctx context.Context, state interface{}) (*http.Request, error)

func (*Httper) RouteRequest

func (h *Httper) RouteRequest(ctx context.Context) (*http.Request, error)

type Logger

type Logger struct {
	MinExecutionMs *int
}

type Metrics

type Metrics struct {
	URI     string
	Metrics []*response.Metric
}

func NewMetrics

func NewMetrics(URI string, metrics []*response.Metric) *Metrics

type Resource

type Resource struct {
	URL         string   `json:",omitempty" yaml:",omitempty"`
	SourceURL   string   `json:",omitempty"`
	With        []string //list of resource to inherit from  `json:",omitempty"`
	Routes      Routes
	Compression *path.Compression `json:",omitempty"`
	Redirect    *path.Redirect    `json:",omitempty"`
	Logger      *path.Logger      `json:",omitempty"` //connect, dataview, time, SQL with params if exceeded time  `json:",omitempty"`
	Cors        *path.Cors        `json:",omitempty"`

	ColumnsCache *discover.Columns `json:",omitempty"`
	RevealMetric *bool             `json:",omitempty"`

	ColumnsDiscovery bool  `json:",omitempty"`
	EnableDebug      *bool `json:",omitempty"`

	Resource *view.Resource
	// contains filtered or unexported fields
}

deprecated TODO replace with repository.Components

func (*Resource) Init

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

type ResponseWithMetrics

type ResponseWithMetrics struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

func NewMetricResponse

func NewMetricResponse(writer http.ResponseWriter) *ResponseWithMetrics

func NewMetricResponseWithTime

func NewMetricResponseWithTime(writer http.ResponseWriter, start time.Time) *ResponseWithMetrics

func (*ResponseWithMetrics) Write

func (r *ResponseWithMetrics) Write(data []byte) (int, error)

func (*ResponseWithMetrics) WriteHeader

func (r *ResponseWithMetrics) WriteHeader(statusCode int)

type Route

type Route struct {
	APIKey      *path.APIKey      `json:",omitempty"`
	Cors        *path.Cors        `json:",omitempty"`
	Internal    bool              `json:"Internal,omitempty" yaml:"Internal,omitempty" `
	ContentURL  string            `json:"ContentURL,omitempty" yaml:"ContentURL,omitempty" `
	EnableAudit bool              `json:",omitempty"`
	EnableDebug *bool             `json:",omitempty"`
	Compression *path.Compression `json:",omitempty"`

	Transforms marshal.Transforms `json:",omitempty"`

	repository.Component
	// contains filtered or unexported fields
}

deprecated

func (*Route) AddApiKeys

func (r *Route) AddApiKeys(keys ...*path.APIKey)

func (*Route) CorsEnabled

func (r *Route) CorsEnabled() bool

func (*Route) HttpURI

func (r *Route) HttpURI() string

func (*Route) Init

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

func (*Route) IsCacheDisabled

func (r *Route) IsCacheDisabled(req *http.Request) bool

func (*Route) IsMetricDebug

func (r *Route) IsMetricDebug(req *http.Request) bool

func (*Route) IsMetricInfo

func (r *Route) IsMetricInfo(req *http.Request) bool

func (*Route) IsMetricsEnabled

func (r *Route) IsMetricsEnabled(req *http.Request) bool

func (*Route) PgkPath

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

func (*Route) SetRouteLookup

func (r *Route) SetRouteLookup(lookup func(route *http2.Route) (*Route, error))

func (*Route) UnmarshalFunc

func (r *Route) UnmarshalFunc(request *http.Request) shared.Unmarshal

TODO move/merge with content.UnmarshalFunc possible remove marshaller interceptors all together

type Routes

type Routes []*Route

deprecated

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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