engine

package
v0.0.0-...-00d32dd Latest Latest
Warning

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

Go to latest
Published: Apr 10, 2019 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Overview

Package engine contains all the required for building and running an API2HTML server

func Run(cfgPath string, devel bool) error {
 	errNilEngine := fmt.Errorf("serve cmd aborted: nil engine")
 	e, err := engine.New(cfgPath, devel)
 	if err != nil {
 		log.Println("engine creation aborted:", err.Error())
 		return err
 	}
 	if e == nil {
 		log.Println("engine creation aborted:", errNilEngine.Error())
 		return errNilEngine
 	}

 	time.Sleep(time.Second)

 	return eW.Run(fmt.Sprintf(":%d", port))
}

Index

Examples

Constants

This section is empty.

Variables

View Source
var Default404StaticHandler = StaticHandler{[]byte(default404Tmpl)}

Default404StaticHandler is the default static handler for dealing with 404 errors

View Source
var Default500StaticHandler = ErrorHandler{[]byte(default500Tmpl), http.StatusInternalServerError}

Default500StaticHandler is the default static handler for dealing with 500 errors

View Source
var DefaultFactory = Factory{
	TemplateStoreFactory: NewTemplateStore,
	Parser:               ParseConfigFromFile,
	MustachePageFactory:  NewMustachePageFactory,
	StaticHandlerFactory: NewStaticHandler,
	ErrorHandlerFactory:  NewErrorHandler,
}

DefaultFactory is an Factory ready to be used

View Source
var DefaultHandlerConfig = HandlerConfig{
	Page{},
	EmptyRenderer,
	NoopResponse,
	"public, max-age=3600",
}

DefaultHandlerConfig contains the dafult values for a HandlerConfig

EmptyRenderer is the Renderer to be use if no other is defined

View Source
var ErrNoBackendDefined = fmt.Errorf("no backend defined")

ErrNoBackendDefined is the error returned when no Backend has been defined

View Source
var ErrNoRendererDefined = fmt.Errorf("no rendered defined")

ErrNoRendererDefined is the error returned when no Renderer has been defined

View Source
var ErrNoResponseGeneratorDefined = fmt.Errorf("no response generator defined")

ErrNoResponseGeneratorDefined is the error returned when no ResponseGenerator has been defined

Functions

func JSONArrayDecoder

func JSONArrayDecoder(r io.Reader, c *ResponseContext) error

JSONArrayDecoder decodes the reader content and puts it into the Array property of the injected ResponseContext

func JSONDecoder

func JSONDecoder(r io.Reader, c *ResponseContext) error

JSONDecoder decodes the reader content and puts it into the Data property of the injected ResponseContext

func New

func New(cfgPath string, devel bool) (*gin.Engine, error)

New creates a gin engine with the default Factory

func NewMustacheRendererMap

func NewMustacheRendererMap(cfg Config) (map[string]*MustacheRenderer, error)

NewMustacheRendererMap returns a map with all renderers for the declared templates and layouts and an error if something went wrong

Types

type Backend

type Backend func(params map[string]string, headers map[string]string, c *gin.Context) (*http.Response, error)

Backend defines the signature of the function that creates a response for a request to a given backend

func CachedClient

func CachedClient(URLPattern string) Backend

CachedClient returns a Dackend to the received URLPattern with a in-memory cache aware http client

func DefaultClient

func DefaultClient(URLPattern string) Backend

DefaultClient returns a Dackend to the received URLPattern with the default http client from the stdlib

func NewBackend

func NewBackend(client *http.Client, URLPattern string) Backend

NewBackend creates a Backend with the received http client and url pattern

type Config

type Config struct {
	Pages            []Page                 `json:"pages"`
	StaticTXTContent []string               `json:"static_txt_content"`
	Robots           bool                   `json:"robots"`
	Sitemap          bool                   `json:"sitemap"`
	Templates        map[string]string      `json:"templates"`
	Layouts          map[string]string      `json:"layouts"`
	Extra            map[string]interface{} `json:"extra"`
	PublicFolder     *PublicFolder          `json:"public_folder"`
	NewRelic         *NewRelic              `json:"newrelic"`
}

Config is a struct with all the required definitions for building an API2HTML engine

func ParseConfig

func ParseConfig(r io.Reader) (Config, error)

ParseConfig parses the content of the reader into a Config

func ParseConfigFromFile

func ParseConfigFromFile(path string) (Config, error)

ParseConfigFromFile creates a Config with the contents of the received filepath

type Decoder

type Decoder func(io.Reader, *ResponseContext) error

Decoder defines the signature for response decoder functions

type DynamicResponseGenerator

type DynamicResponseGenerator struct {
	Page    Page
	Backend Backend
	Decoder Decoder
}

DynamicResponseGenerator is a ResponseGenerator that creates a response by adding the decoded data returned by the Backend wo the default response values. Depending on the selected decoder, the generated responses may have the backend data stored at the `Obj` or at the `Arr` part

func (*DynamicResponseGenerator) ResponseGenerator

func (drg *DynamicResponseGenerator) ResponseGenerator(c *gin.Context) (ResponseContext, error)

ResponseGenerator implements the ResponseGenerator interface

type ErrorHandler

type ErrorHandler struct {
	Content   []byte
	ErrorCode int
}

ErrorHandler is a Handler that writes the injected content. It's intended to be dispatched by the gin special handlers (NoRoute, NoMethod) but they can also be used as regular handlers

func NewErrorHandler

func NewErrorHandler(path string, code int) (ErrorHandler, error)

NewErrorHandler creates a ErrorHandler using the content of the received path

func (*ErrorHandler) HandlerFunc

func (e *ErrorHandler) HandlerFunc() gin.HandlerFunc

HandlerFunc is a gin middleware for dealing with some errors

type ErrorRenderer

type ErrorRenderer struct {
	Error error
}

ErrorRenderer is a renderer that always returns the injected error

func (ErrorRenderer) Render

func (r ErrorRenderer) Render(_ io.Writer, _ interface{}) error

Render implements the Renderer interface by returning the injected error

type Factory

type Factory struct {
	TemplateStoreFactory func() *TemplateStore
	Parser               func(string) (Config, error)
	MustachePageFactory  func(*gin.Engine, *TemplateStore) MustachePageFactory
	StaticHandlerFactory func(string) (StaticHandler, error)
	ErrorHandlerFactory  func(string, int) (ErrorHandler, error)
}

Factory is a struct able to build api2html engines

func (Factory) New

func (ef Factory) New(cfgPath string, devel bool) (*gin.Engine, error)

New creates a gin engine with the received config and the injected factories

type Handler

type Handler struct {
	Page              Page
	Renderer          Renderer
	Input             chan Renderer
	Subscribe         chan Subscription
	ResponseGenerator ResponseGenerator
	CacheControl      string
}

Handler is a struct that combines a renderer and a response generator for handling http requests.

The handler is able to keep itself subscribed to the last renderer version to use by wrapping its Input channel into a Subscription and sending it through the Subscribe channel every time it gets a new Renderer

func NewHandler

func NewHandler(cfg HandlerConfig, subscriptionChan chan Subscription) *Handler

NewHandler creates a Handler with the given configuration. The returned handler will be keeping itself subscribed to the latest template updates using the given subscription channel, allowing hot template reloads

func (*Handler) HandlerFunc

func (h *Handler) HandlerFunc(c *gin.Context)

HandlerFunc handles a gin request rendering the data returned by the response generator. If the response generator does not return an error, it adds a Cache-Control header

type HandlerConfig

type HandlerConfig struct {
	// Page contains the page description
	Page Page
	// Renderer is the component responsible for rendering the responses
	Renderer Renderer
	// ResponseGenerator gets the data required for generating a response
	// it can get it from a static, local source or from a remote api
	// endpoint
	ResponseGenerator ResponseGenerator
	// CacheControl is the Cache-Control string added into the response headers
	// if everything goes ok
	CacheControl string
}

HandlerConfig defines a Handler

func NewHandlerConfig

func NewHandlerConfig(page Page) HandlerConfig

NewHandlerConfig creates a HandlerConfig from the given Page definition

type LayoutMustacheRenderer

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

LayoutMustacheRenderer is a mustache renderer composing a mustache template with a layout

func NewLayoutMustacheRenderer

func NewLayoutMustacheRenderer(t, l io.Reader) (*LayoutMustacheRenderer, error)

NewLayoutMustacheRenderer returns a LayoutMustacheRenderer and an error if something went wrong

func (LayoutMustacheRenderer) Render

func (m LayoutMustacheRenderer) Render(w io.Writer, v interface{}) error

Render implements the renderer interface

type MustachePageFactory

type MustachePageFactory struct {
	Engine        *gin.Engine
	TemplateStore *TemplateStore
}

MustachePageFactory is a component that sets up the gin engine and the template store

func NewMustachePageFactory

func NewMustachePageFactory(e *gin.Engine, ts *TemplateStore) MustachePageFactory

NewMustachePageFactory creates a MustachePageFactory with the injected params

func (*MustachePageFactory) Build

func (m *MustachePageFactory) Build(cfg Config)

Build sets up the injected gin engine and template store depending on the contents of the received configuration

type MustacheRenderer

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

MustacheRenderer is a simple mustache renderer with a single mustache template

func NewMustacheRenderer

func NewMustacheRenderer(r io.Reader) (*MustacheRenderer, error)

NewMustacheRenderer returns a MustacheRenderer and an error if something went wrong

func (MustacheRenderer) Render

func (m MustacheRenderer) Render(w io.Writer, v interface{}) error

Render implements the renderer interface

type NewRelic

type NewRelic struct {
	AppName string `json:"app_name"`
	License string `json:"license"`
}

NewRelic contains the info regarding the app name and the newrelic license key

type Page

type Page struct {
	Name              string
	URLPattern        string
	BackendURLPattern string
	Template          string
	Layout            string
	CacheTTL          string
	Header            string
	IsArray           bool
	Extra             map[string]interface{}
}

Page defines the behaviour of the engine for a given URL pattern

type PublicFolder

type PublicFolder struct {
	Path   string `json:"path_to_folder"`
	Prefix string `json:"url_prefix"`
}

PublicFolder contains the info regarding the static contents to be served

type Renderer

type Renderer interface {
	Render(io.Writer, interface{}) error
}

Renderer defines the interface for the template renderers

type RendererFunc

type RendererFunc func(io.Writer, interface{}) error

RendererFunc is a function implementing the Renderer interface

func (RendererFunc) Render

func (rf RendererFunc) Render(w io.Writer, v interface{}) error

Render implements the Renderer interface

type ResponseContext

type ResponseContext struct {
	// Data cotains the backend data if the response was decoded as a struct
	Data map[string]interface{}
	// Array cotains the backend data if the response was decoded as an array
	Array []map[string]interface{}
	// Extra contains the extra data injected from the config
	Extra map[string]interface{}
	// Params stores the params of the request
	Params map[string]string
	// Helper is a struct containing a few basic template helpers
	Helper interface{} `json:"-"`
	// 	Context is a reference to the gin context for the request
	Context *gin.Context `json:"-"`
}

ResponseContext is the struct ready to rendered and returned to the Handler

func NoopResponse

func NoopResponse(_ *gin.Context) (ResponseContext, error)

NoopResponse is a ResponseGenerator that always returns an empty response and the ErrNoResponseGeneratorDefined error

func (*ResponseContext) String

func (r *ResponseContext) String() string

String implements the Stringer interface

Example
r := ResponseContext{
	Data: map[string]interface{}{
		"a": "foo",
		"b": 42,
	},
	Params: map[string]string{"p1": "v1"},
	Extra: map[string]interface{}{
		"extra1": "foo",
		"extra2": 42,
	},
}
fmt.Println(r.String())
Output:

{
	"Data": {
		"a": "foo",
		"b": 42
	},
	"Array": null,
	"Extra": {
		"extra1": "foo",
		"extra2": 42
	},
	"Params": {
		"p1": "v1"
	}
}

type ResponseGenerator

type ResponseGenerator func(*gin.Context) (ResponseContext, error)

ResponseGenerator is a function that, given a gin request, returns a response struc and an error

type StaticHandler

type StaticHandler struct {
	Content []byte
}

StaticHandler is a Handler that writes the injected content

func NewStaticHandler

func NewStaticHandler(path string) (StaticHandler, error)

NewStaticHandler creates a StaticHandler using the content of the received path

func (*StaticHandler) HandlerFunc

func (e *StaticHandler) HandlerFunc() gin.HandlerFunc

HandlerFunc creates a gin handler that does nothing but writing the static content

type StaticResponseGenerator

type StaticResponseGenerator struct {
	Page Page
}

StaticResponseGenerator is a ResponseGenerator that creates a response just by adding the default response values to the ResponseContext and a zero value BackendData

func (*StaticResponseGenerator) ResponseGenerator

func (s *StaticResponseGenerator) ResponseGenerator(c *gin.Context) (ResponseContext, error)

ResponseGenerator implements the ResponseGenerator interface

type Subscription

type Subscription struct {
	// Name is the name to watch
	Name string
	// In is the channel where the new renderer should be sent after a change
	In chan Renderer
}

Subscription is a struct to be used to be notified after a change in the watched renderer

type TemplateStore

type TemplateStore struct {
	Subscribe chan Subscription
	// contains filtered or unexported fields
}

TemplateStore manages the loaded templates and the subscriptions

func NewTemplateStore

func NewTemplateStore() *TemplateStore

NewTemplateStore creates a TemplateStore ready to be used

The returned TemplateStore will be accepting and managing subscriptions

func (TemplateStore) Get

func (p TemplateStore) Get(name string) (Renderer, bool)

Get returns a Renderer and a boolean signaling if the given name is not in the store

func (*TemplateStore) Set

func (p *TemplateStore) Set(name string, tmpl Renderer) error

Set adds or updates the renderer with the given name. After updating its internal state, it alerts all the subscriptors by sending the new renderer and removes all the subscriptions.

Jump to

Keyboard shortcuts

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