Documentation
¶
Index ¶
- Constants
- Variables
- func Download(url url.URL, outputFilepath string, parallelism int, tlsSkipVerify bool, ...) (*time.Duration, error)
- func RenderProblem(kind ProblemKind, w http.ResponseWriter, details ...string)
- func RenderProblemAndLog(kind ProblemKind, w http.ResponseWriter, err error, details ...string)
- func SafeWrite(write func([]byte) (int, error), body []byte)
- type Breadcrumb
- type ContentNegotiation
- func (cn *ContentNegotiation) GetStyleFormatExtension(format string) string
- func (cn *ContentNegotiation) GetSupportedStyleFormats() []string
- func (cn *ContentNegotiation) NegotiateFormat(req *http.Request) string
- func (cn *ContentNegotiation) NegotiateLanguage(w http.ResponseWriter, req *http.Request) language.Tag
- type Engine
- func (e *Engine) ParseTemplate(key TemplateKey)
- func (e *Engine) RebuildOpenAPI(openAPIParams any)
- func (e *Engine) RegisterShutdownHook(fn func())
- func (e *Engine) RenderAndServe(w http.ResponseWriter, r *http.Request, key TemplateKey, params any, ...)
- func (e *Engine) RenderTemplates(urlPath string, breadcrumbs []Breadcrumb, keys ...TemplateKey)
- func (e *Engine) RenderTemplatesWithParams(urlPath string, params any, breadcrumbs []Breadcrumb, keys ...TemplateKey)
- func (e *Engine) ReverseProxy(w http.ResponseWriter, r *http.Request, target *url.URL, prefer204 bool, ...)
- func (e *Engine) ReverseProxyAndValidate(w http.ResponseWriter, r *http.Request, target *url.URL, prefer204 bool, ...)
- func (e *Engine) Serve(w http.ResponseWriter, r *http.Request, opt ...ServeOption)
- func (e *Engine) Start(address string, debugPort int, shutdownDelay int) error
- func (e *Engine) WithNegotiatedLanguage(w http.ResponseWriter, r *http.Request) TemplateKeyOption
- type OpenAPI
- type OutputFormat
- type Part
- type ProblemKind
- type ServeOption
- type TemplateData
- type TemplateKey
- type TemplateKeyOption
- type Templates
Constants ¶
const ( FormatParam = "f" MediaTypeJSON = "application/json" MediaTypeXML = "application/xml" 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 MediaTypeJSONSchema = "application/schema+json" MediaTypeQuantizedMesh = "application/vnd.quantized-mesh" FormatHTML = "html" FormatXML = "xml" FormatJSON = "json" FormatTileJSON = "tilejson" FormatMVT = "mvt" FormatMVTAlternative = "pbf" FormatMapboxStyle = "mapbox" FormatSLD = "sld10" FormatGeoJSON = "geojson" // ?=json should also work for geojson FormatJSONFG = "jsonfg" FormatGzip = "gzip" )
const ( HeaderLink = "Link" HeaderAccept = "Accept" HeaderAcceptLanguage = "Accept-Language" HeaderAcceptRanges = "Accept-Ranges" HeaderRange = "Range" HeaderContentType = "Content-Type" HeaderContentLength = "Content-Length" HeaderContentCrs = "Content-Crs" HeaderContentEncoding = "Content-Encoding" HeaderBaseURL = "X-BaseUrl" HeaderRequestedWith = "X-Requested-With" HeaderAPIVersion = "API-Version" )
const (
HTMLRegex = `<[/]?([a-zA-Z]+).*?>`
)
Variables ¶
var ( MediaTypeJSONFamily = []string{ MediaTypeTileJSON, MediaTypeMapboxStyle, MediaTypeGeoJSON, MediaTypeJSONFG, MediaTypeJSONSchema, } CompressibleMediaTypes = []string{ MediaTypeJSON, MediaTypeGeoJSON, MediaTypeJSONFG, MediaTypeTileJSON, MediaTypeJSONSchema, MediaTypeMapboxStyle, MediaTypeOpenAPI, MediaTypeHTML, "text/css", "text/plain", "text/javascript", "application/javascript", "image/svg+xml", } OutputFormatDefault = []OutputFormat{ {Key: FormatJSON, Name: "JSON"}, } StyleFormatExtension = map[string]string{ FormatMapboxStyle: ".json", FormatSLD: ".sld", } )
var ( ProblemBadRequest = ProblemKind(http.StatusBadRequest) ProblemNotFound = ProblemKind(http.StatusNotFound) ProblemNotAcceptable = ProblemKind(http.StatusNotAcceptable) ProblemServerError = ProblemKind(http.StatusInternalServerError) ProblemBadGateway = ProblemKind(http.StatusBadGateway) )
The following problems should be added to openapi/problems.go.json.
var (
GlobalTemplateFuncs texttemplate.FuncMap
)
var Now = time.Now // allow mocking
Functions ¶
func Download ¶ added in v0.50.0
func Download(url url.URL, outputFilepath string, parallelism int, tlsSkipVerify bool, timeout time.Duration, retryDelay time.Duration, retryMaxDelay time.Duration, maxRetries int) (*time.Duration, error)
Download downloads file from the given URL and stores the result in the given output location. Will utilize multiple concurrent connections to increase transfer speed. The latter is only possible when the remote server supports HTTP Range Requests, otherwise it falls back to a regular/single connection download. Additionally, failed requests will be retried according to the given settings.
func RenderProblem ¶
func RenderProblem(kind ProblemKind, w http.ResponseWriter, details ...string)
RenderProblem writes RFC 7807 (https://tools.ietf.org/html/rfc7807) problem to the client. Only the listed problem kinds are supported since they should be advertised in the OpenAPI spec. Optionally, a caller may add details (single string) about the problem. Warning: Be sure to not include sensitive information in the details string!
func RenderProblemAndLog ¶ added in v0.54.2
func RenderProblemAndLog(kind ProblemKind, w http.ResponseWriter, err error, details ...string)
RenderProblemAndLog writes RFC 7807 (https://tools.ietf.org/html/rfc7807) problem to client + logs message to stdout.
Types ¶
type Breadcrumb ¶
type ContentNegotiation ¶
type ContentNegotiation struct {
// contains filtered or unexported fields
}
ContentNegotiation handles HTTP content negotiation. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Content_negotiation
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-OGCAPI specific logic.
func NewEngine ¶
func NewEngine(configFile string, themeFile string, openAPIFile string, enableTrailingSlash bool, enableCORS bool) (*Engine, error)
NewEngine builds a new Engine.
func NewEngineWithConfig ¶
func NewEngineWithConfig(config *config.Config, theme *config.Theme, 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 RenderAndServe.
func (*Engine) RebuildOpenAPI ¶
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) RenderAndServe ¶ added in v0.75.0
func (e *Engine) RenderAndServe(w http.ResponseWriter, r *http.Request, key TemplateKey, params any, breadcrumbs []Breadcrumb, availableFormats []OutputFormat)
RenderAndServe renders an already parsed HTML or non-HTML template on-the-fly depending on the format in the given TemplateKey. The result isn't stored 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 datastore), otherwise use ServePage for pre-rendered pages.
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(urlPath string, params any, breadcrumbs []Breadcrumb, keys ...TemplateKey)
RenderTemplatesWithParams renders both HTML and non-HTML templates depending on the format given in the TemplateKey.
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 ¶
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) Serve ¶ added in v0.57.0
func (e *Engine) Serve(w http.ResponseWriter, r *http.Request, opt ...ServeOption)
Serve serves a response (which is either a pre-rendered template based on TemplateKey or a slice of arbitrary bytes) while also validating against the OpenAPI spec.
func (*Engine) WithNegotiatedLanguage ¶ added in v0.75.0
func (e *Engine) WithNegotiatedLanguage(w http.ResponseWriter, r *http.Request) TemplateKeyOption
WithNegotiatedLanguage sets the language of a TemplateKey based on content-negotiation.
type OutputFormat ¶ added in v1.2.0
OutputFormat formats that can be returned by the API.
type Part ¶ added in v0.50.0
Part piece of the file to download when HTTP Range Requests are supported.
type ProblemKind ¶ added in v0.48.2
type ProblemKind int
type ServeOption ¶ added in v0.75.0
type ServeOption func(*serve)
func ServeContentType ¶ added in v0.75.0
func ServeContentType(contentType string) ServeOption
func ServeJSON ¶ added in v1.5.0
func ServeJSON(json any) ServeOption
func ServePreRenderedOutput ¶ added in v1.5.0
func ServePreRenderedOutput(output []byte) ServeOption
func ServeTemplate ¶ added in v0.75.0
func ServeTemplate(templateKey TemplateKey) ServeOption
func ServeValidation ¶ added in v0.75.0
func ServeValidation(validateRequest bool, validateResponse bool) ServeOption
type TemplateData ¶
type TemplateData struct {
// Config set during startup based on the given config file
Config *config.Config
// Theme set during startup
Theme *config.Theme
// 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
// AvailableFormats returns the output formats available for the current page
AvailableFormats []OutputFormat
// contains filtered or unexported fields
}
TemplateData the data/variables passed as an argument into the template.
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
// Optional. Use with caution, overwrite the Media-Type associated with the Format of this template.
MediaTypeOverwrite 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, opts ...TemplateKeyOption) TemplateKey
NewTemplateKey builds a TemplateKey with the given path and options.
type TemplateKeyOption ¶ added in v0.75.0
type TemplateKeyOption func(*TemplateKey)
TemplateKeyOption implements the functional option pattern for TemplateKey.
func WithInstanceName ¶ added in v0.75.0
func WithInstanceName(instanceName string) TemplateKeyOption
WithInstanceName sets the instance name of a TemplateKey.
func WithLanguage ¶ added in v0.75.0
func WithLanguage(language language.Tag) TemplateKeyOption
WithLanguage sets the language of a TemplateKey.
func WithMediaTypeOverwrite ¶ added in v0.75.0
func WithMediaTypeOverwrite(mediaType string) TemplateKeyOption
WithMediaTypeOverwrite overwrites the mediatype of the Format in a 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
Theme *config.Theme
// contains filtered or unexported fields
}