engine

package
v0.46.0 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2024 License: MIT Imports: 40 Imported by: 0

Documentation

Index

Constants

View Source
const (
	FormatParam = "f"

	MediaTypeJSON          = "application/json"
	MediaTypeHTML          = "text/html"
	MediaTypeTileJSON      = "application/vnd.mapbox.tile+json"
	MediaTypeMVT           = "application/vnd.mapbox-vector-tile"
	MediaTypeMapboxStyle   = "application/vnd.mapbox.style+json"
	MediaTypeSLD           = "application/vnd.ogc.sld+xml;version=1.0"
	MediaTypeOpenAPI       = "application/vnd.oai.openapi+json;version=3.0"
	MediaTypeGeoJSON       = "application/geo+json"
	MediaTypeJSONFG        = "application/vnd.ogc.fg+json" // https://docs.ogc.org/per/21-017r1.html#toc17
	MediaTypeQuantizedMesh = "application/vnd.quantized-mesh"

	FormatHTML           = "html"
	FormatJSON           = "json"
	FormatTileJSON       = "tilejson"
	FormatMVT            = "mvt"
	FormatMVTAlternative = "pbf"
	FormatMapboxStyle    = "mapbox"
	FormatSLD            = "sld10"
	FormatGeoJSON        = "geojson" // ?=json should also work for geojson
	FormatJSONFG         = "jsonfg"
	FormatGzip           = "gzip"
)
View Source
const (
	HeaderLink            = "Link"
	HeaderAccept          = "Accept"
	HeaderAcceptLanguage  = "Accept-Language"
	HeaderContentType     = "Content-Type"
	HeaderContentLength   = "Content-Length"
	HeaderContentCrs      = "Content-Crs"
	HeaderContentEncoding = "Content-Encoding"
	HeaderBaseURL         = "X-BaseUrl"
	HeaderRequestedWith   = "X-Requested-With"
	HeaderAPIVersion      = "API-Version"
)
View Source
const (
	HTMLRegex = `<[/]?([a-zA-Z]+).*?>`
)

Variables

View Source
var (
	MediaTypeJSONFamily    = []string{MediaTypeTileJSON, MediaTypeMapboxStyle, MediaTypeGeoJSON, MediaTypeJSONFG}
	OutputFormatDefault    = map[string]string{FormatJSON: "JSON"}
	OutputFormatFeatures   = map[string]string{FormatJSON: "GeoJSON", FormatJSONFG: "JSON-FG"}
	CompressibleMediaTypes = []string{
		MediaTypeJSON,
		MediaTypeGeoJSON,
		MediaTypeJSONFG,
		MediaTypeTileJSON,
		MediaTypeMapboxStyle,
		MediaTypeOpenAPI,
		MediaTypeHTML,

		"text/css",
		"text/plain",
		"text/javascript",
		"application/javascript",
		"image/svg+xml",
	}
	StyleFormatExtension = map[string]string{
		FormatMapboxStyle: ".json",
		FormatSLD:         ".sld",
	}
)
View Source
var (
	ProblemBadRequest    = problem.Of(http.StatusBadRequest)
	ProblemNotFound      = problem.Of(http.StatusNotFound)
	ProblemNotAcceptable = problem.Of(http.StatusNotAcceptable)
	ProblemServerError   = problem.Of(http.StatusInternalServerError).Append(problem.Detail(defaultMessageServerErr))
	ProblemBadGateway    = problem.Of(http.StatusBadGateway).Append(problem.Detail(defaultMessageBadGateway))
)

The following problems should be added to openapi/problems.go.json

View Source
var Now = time.Now // allow mocking

Functions

func RenderProblem added in v0.44.0

func RenderProblem(p *problem.Problem, w http.ResponseWriter, details ...string)

func SafeWrite

func SafeWrite(write func([]byte) (int, error), body []byte)

SafeWrite executes the given http.ResponseWriter.Write while logging errors

Types

type Breadcrumb struct {
	Name string
	Path string
}

type ContentNegotiation

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

func (*ContentNegotiation) GetStyleFormatExtension

func (cn *ContentNegotiation) GetStyleFormatExtension(format string) string

func (*ContentNegotiation) GetSupportedStyleFormats

func (cn *ContentNegotiation) GetSupportedStyleFormats() []string

func (*ContentNegotiation) NegotiateFormat

func (cn *ContentNegotiation) NegotiateFormat(req *http.Request) string

NegotiateFormat performs content negotiation, not idempotent (since it removes the ?f= param)

func (*ContentNegotiation) NegotiateLanguage

func (cn *ContentNegotiation) NegotiateLanguage(w http.ResponseWriter, req *http.Request) language.Tag

NegotiateLanguage performs language negotiation, not idempotent (since it removes the ?lang= param)

type Engine

type Engine struct {
	Config    *config.Config
	OpenAPI   *OpenAPI
	Templates *Templates
	CN        *ContentNegotiation
	Router    *chi.Mux
	// contains filtered or unexported fields
}

Engine encapsulates shared non-OGC API specific logic

func NewEngine

func NewEngine(configFile string, openAPIFile string, enableTrailingSlash bool, enableCORS bool) (*Engine, error)

NewEngine builds a new Engine

func NewEngineWithConfig

func NewEngineWithConfig(config *config.Config, openAPIFile string, enableTrailingSlash bool, enableCORS bool) *Engine

NewEngineWithConfig builds a new Engine

func (*Engine) ParseTemplate

func (e *Engine) ParseTemplate(key TemplateKey)

ParseTemplate parses both HTML and non-HTML templates depending on the format given in the TemplateKey and stores it in the engine for future rendering using RenderAndServePage.

func (*Engine) RebuildOpenAPI

func (e *Engine) RebuildOpenAPI(openAPIParams any)

RebuildOpenAPI rebuild the full OpenAPI spec with the newly given parameters. Use only once during bootstrap for specific use cases! For example: when you want to expand a specific part of the OpenAPI spec with data outside the configuration file (e.g. from a database).

func (*Engine) RegisterShutdownHook

func (e *Engine) RegisterShutdownHook(fn func())

RegisterShutdownHook register a func to execute during graceful shutdown, e.g. to clean up resources.

func (*Engine) RenderAndServePage

func (e *Engine) RenderAndServePage(w http.ResponseWriter, r *http.Request, key TemplateKey,
	params any, breadcrumbs []Breadcrumb)

RenderAndServePage renders an already parsed HTML or non-HTML template and renders it on-the-fly depending on the format in the given TemplateKey. The result isn't store in engine, it's served directly to the client.

NOTE: only used this for dynamic pages that can't be pre-rendered and cached (e.g. with data from a backing store).

func (*Engine) RenderTemplates

func (e *Engine) RenderTemplates(urlPath string, breadcrumbs []Breadcrumb, keys ...TemplateKey)

RenderTemplates renders both HTML and non-HTML templates depending on the format given in the TemplateKey. This method also performs OpenAPI validation of the rendered template, therefore we also need the URL path. The rendered templates are stored in the engine for future serving using ServePage.

func (*Engine) RenderTemplatesWithParams

func (e *Engine) RenderTemplatesWithParams(params any, breadcrumbs []Breadcrumb, keys ...TemplateKey)

RenderTemplatesWithParams renders both HTMl and non-HTML templates depending on the format given in the TemplateKey. This method does not perform OpenAPI validation of the rendered template (will be done during runtime).

func (*Engine) ReverseProxy

func (e *Engine) ReverseProxy(w http.ResponseWriter, r *http.Request, target *url.URL,
	prefer204 bool, contentTypeOverwrite string)

ReverseProxy forwards given HTTP request to given target server, and optionally tweaks response

func (*Engine) ReverseProxyAndValidate added in v0.44.0

func (e *Engine) ReverseProxyAndValidate(w http.ResponseWriter, r *http.Request, target *url.URL,
	prefer204 bool, contentTypeOverwrite string, validateResponse bool)

ReverseProxyAndValidate forwards given HTTP request to given target server, and optionally tweaks and validates response

func (*Engine) ServePage

func (e *Engine) ServePage(w http.ResponseWriter, r *http.Request, templateKey TemplateKey)

ServePage serves a pre-rendered template while also validating against the OpenAPI spec

func (*Engine) ServeResponse

func (e *Engine) ServeResponse(w http.ResponseWriter, r *http.Request,
	validateRequest bool, validateResponse bool, contentType string, response []byte)

ServeResponse serves the given response (arbitrary bytes) while also validating against the OpenAPI spec

func (*Engine) Start

func (e *Engine) Start(address string, debugPort int, shutdownDelay int) error

Start the engine by initializing all components and starting the server

type OpenAPI

type OpenAPI struct {
	SpecJSON []byte
	// contains filtered or unexported fields
}

func (*OpenAPI) ValidateRequest

func (o *OpenAPI) ValidateRequest(r *http.Request) error

func (*OpenAPI) ValidateResponse

func (o *OpenAPI) ValidateResponse(contentType string, body []byte, r *http.Request) error

type TemplateData

type TemplateData struct {
	// Config set during startup based on the given config file
	Config *config.Config

	// Params optional parameters not part of GoKoala's config file. You can use
	// this to provide extra data to a template at rendering time.
	Params any

	// Breadcrumb path to the page, in key-value pairs of name->path
	Breadcrumbs []Breadcrumb
	// contains filtered or unexported fields
}

TemplateData the data/variables passed as an argument into the template.

func (*TemplateData) AvailableFormats

func (td *TemplateData) AvailableFormats() map[string]string

AvailableFormats returns the output formats available for the current page

func (*TemplateData) AvailableFormatsFeatures

func (td *TemplateData) AvailableFormatsFeatures() map[string]string

AvailableFormatsFeatures convenience function

func (*TemplateData) QueryString

func (td *TemplateData) QueryString(format string) string

QueryString returns ?=foo=a&bar=b style query string of the current page

type TemplateKey

type TemplateKey struct {
	// Name of the template, the filename including extension
	Name string

	// Directory in which the template resides
	Directory string

	// Format the file format based on the filename extension, 'html' or 'json'
	Format string

	// Language of the contents of the template
	Language language.Tag

	// Optional. Only required when you want to render the same template multiple times (with different content).
	// By specifying an 'instance name' you can refer to a certain instance of a rendered template later on.
	InstanceName string
}

TemplateKey unique key to register and lookup Go templates

func ExpandTemplateKey

func ExpandTemplateKey(key TemplateKey, language language.Tag) TemplateKey

func NewTemplateKey

func NewTemplateKey(path string) TemplateKey

NewTemplateKey build TemplateKeys

func NewTemplateKeyWithLanguage

func NewTemplateKeyWithLanguage(path string, language language.Tag) TemplateKey

func NewTemplateKeyWithName

func NewTemplateKeyWithName(path string, instanceName string) TemplateKey

NewTemplateKeyWithName build TemplateKey with InstanceName (see docs in struct)

func NewTemplateKeyWithNameAndLanguage

func NewTemplateKeyWithNameAndLanguage(path string, instanceName string, language language.Tag) TemplateKey

type Templates

type Templates struct {
	// ParsedTemplates templates loaded from disk and parsed to an in-memory Go representation.
	ParsedTemplates map[TemplateKey]any

	// RenderedTemplates templates parsed + rendered to their actual output format like JSON, HTMl, etc.
	// We prefer pre-rendered templates whenever possible. These are stored in this map.
	RenderedTemplates map[TemplateKey][]byte
	// contains filtered or unexported fields
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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