flamingo

package
v3.0.0-alpha6 Latest Latest
Warning

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

Go to latest
Published: Feb 22, 2019 License: OSL-3.0 Imports: 10 Imported by: 140

README

Events

Flamingo uses a builtin event router, which routes events for each request.

This means that events are request-scoped, so you can assume that fired events should not cross request boundaries (and are bound to the same go routine).

Event interfaces

An Event can be everything, usually a struct with a few fields.

LoginSucessEvent struct {
    UserId string
}

Events should not have the current context in them!

Firing events

An Event is fired using the EventRouter

type (
    IndexController struct {
       EventRouter    event.Router                 `inject:""`
    }
    
    MyEvent struct {
        Data string
    }
)

func (controller *IndexController) Get(ctx web.Context) web.Response {
    controller.EventRouter.Dispatch(ctx, &MyEvent{Data: "Hello"})
}

Subscribing to events

To listen to Events you need to create a "Subscriber". A Subscriber will get all Events and need to decide which Events it want to handle:

type (
    type EventSubscriber struct {}
)


//Notify should get called by flamingo Eventlogic
func (e *EventSubscriber) NotifyWithContext(ctx context.Context, event event.Event) {
    switch event := event.(type) {
    case *MyEvent:
        subscriber.OnMyEvent(event)  // call event handler and do something
    }
}

Currently Flamingo uses Dingo Multibindings to register Event Subscriber

func (m *Module) Configure(injector *dingo.Injector) {
    flamingo.BindEventSubscriber(injector).To(application.EventSubscriber{})
}

There is also the interface SubscriberWithContextas well as an interface Subscriber that you can use when you don't need the current request context.

Sessions

General session usage

Session handling in Flamingo is bound to the web.Context.

web.Context has a Session() method returning a gorilla.Session object, which the programmer can assume is properly persisted and handled.

Sessions have a Values map of type map[string]interface{}, which can be used to store arbitrary data.

However, it is important to know that underlying gob is used, so it might be necessary to register your custom types via gob.Register(MyStruct{}) in your module's Configure method if you want to make sure it is properly persisted.

Persistence is done automatically if you use Values.

Authentication

Flamingo's core/auth module provides basic OpenID connect authentication.

Given that the module is used in your project (that means registered) you can inject the application.AuthManager in your controller, and use that to retrieve User information from the context.

Please note: the auth package needs a proper session backend like redis, the cookie backend does not provide enough space for jwt tokens.

import (
    "go.aoe.com/flamingo/core/auth/application"
    "go.aoe.com/flamingo/core/auth/domain"
)

type Controller struct {
    AuthManager *application.AuthManager `inject:""`
}

func (c *Controller) Get(ctx web.Context) web.Response {
    token, err := c.AuthManager.IdToken(ctx)
    // ...
    user := domain.UserFromIDToken(token)  // user contains the User information obtained from the ID token
    
    client, err := c.AuthManager.HttpClient(ctx)
    /*
     * client is of type http.Client, and provides
     * a basic http client functionality.
     * If the context belongs to a logged in user
     * then all requests done via this client will have
     * automatically the current OAuth2 Access Token assigned
     */
}

Session Configuration

Flamingo expects a session.Store dingo binding, this is currently handled via the session.backend config parameter.

Possible values are currently file for temporary file storage and redis for a redis backend.

The redis backend uses the config param session.backend.redis.host to find the redis, e.g. redis.host:6379.

Documentation

Index

Constants

View Source
const (
	LogKeyAccesslog         LogKey = "accesslog" // LogKeyAccesslog marks a logmessage belonging to an (incoming) call (value should be 1)
	LogKeyApicall                  = "apicall"   // LogKeyApicall marks a logmessage belonging to an (outgoing) api call (value should be 1)
	LogKeyArea                     = "area"
	LogKeyBusinessID               = "businessId"
	LogKeyCategory                 = "category"
	LogKeySubCategory              = "sub_category"
	LogKeyClientIP                 = "client_ip"
	LogKeyCode                     = "code"
	LogKeyConnectionStatus         = "connection_status"
	LogKeyCorrelationID            = "correlationId"
	LogKeyLevel                    = "level"
	LogKeyMessage                  = "message"
	LogKeyMethod                   = "method"
	LogKeyPath                     = "path"
	LogKeyReferer                  = "referer"
	LogKeyRequest                  = "request"
	LogKeyRequestTime              = "request_time"
	LogKeyRequestedEndpoint        = "requested_endpoint"
	LogKeyRequestedURL             = "requested_url"
	LogKeyResponse                 = "response"
	LogKeyResponseCode             = "response_code"
	LogKeyResponseTime             = "response_time"
	LogKeySource                   = "source"
	LogKeyTimestamp                = "@timestamp"
	LogKeyTrace                    = "trace"
)

Common logger field keys

Variables

This section is empty.

Functions

func BindEventSubscriber

func BindEventSubscriber(injector *dingo.Injector) *dingo.Binding

BindEventSubscriber is a helper to bind a private event Subscriber via Dingo

func BindTemplateFunc

func BindTemplateFunc(injector *dingo.Injector, name string, fnc TemplateFunc)

BindTemplateFunc makes sure a template function is correctly bound via dingo

Types

type DefaultEventRouter

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

DefaultEventRouter is a default event routing implementation

func (*DefaultEventRouter) Dispatch

func (d *DefaultEventRouter) Dispatch(ctx context.Context, event Event)

Dispatch calls the event's Dispatch method on each subscriber

func (*DefaultEventRouter) Inject

func (d *DefaultEventRouter) Inject(provider eventSubscriberProvider)

Inject eventSubscriberProvider dependency

type Event

type Event interface{}

Event defines some event

type EventRouter

type EventRouter interface {
	Dispatch(ctx context.Context, event Event)
}

EventRouter routes events

type LogKey

type LogKey string

LogKey is a logging key constant

type Logger

type Logger interface {
	WithContext(ctx context.Context) Logger

	Debug(args ...interface{})
	Info(args ...interface{})
	Warn(args ...interface{})
	Error(args ...interface{})
	Fatal(args ...interface{})
	Panic(args ...interface{})

	Debugf(log string, args ...interface{})

	WithField(key LogKey, value interface{}) Logger
	WithFields(fields map[LogKey]interface{}) Logger

	Flush()
}

Logger defines a standard Flamingo logger interfaces

type NullLogger

type NullLogger struct{}

NullLogger does not log

func (NullLogger) Debug

func (NullLogger) Debug(args ...interface{})

Debug null-implementation

func (NullLogger) Debugf

func (NullLogger) Debugf(log string, args ...interface{})

Debugf null-implementation

func (NullLogger) Error

func (NullLogger) Error(args ...interface{})

Error null-implementation

func (NullLogger) Fatal

func (NullLogger) Fatal(args ...interface{})

Fatal null-implementation

func (NullLogger) Flush

func (n NullLogger) Flush()

Flush null-implementation

func (NullLogger) Info

func (NullLogger) Info(args ...interface{})

Info null-implementation

func (NullLogger) Panic

func (NullLogger) Panic(args ...interface{})

Panic null-implementation

func (NullLogger) Warn

func (NullLogger) Warn(args ...interface{})

Warn null-implementation

func (NullLogger) WithContext

func (n NullLogger) WithContext(ctx context.Context) Logger

WithContext null-implementation

func (NullLogger) WithField

func (n NullLogger) WithField(key LogKey, value interface{}) Logger

WithField null-implementation

func (NullLogger) WithFields

func (n NullLogger) WithFields(fields map[LogKey]interface{}) Logger

WithFields null-implementation

type PartialTemplateEngine

type PartialTemplateEngine interface {
	RenderPartials(ctx context.Context, templateName string, data interface{}, partials []string) (map[string]io.Reader, error)
}

PartialTemplateEngine is used for progressive enhancements / rendering of partial template areas usually this is requested via the appropriate javascript headers and taken care of in the framework renderer

type SessionModule

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

SessionModule for session management

func (*SessionModule) Configure

func (m *SessionModule) Configure(injector *dingo.Injector)

Configure DI

func (*SessionModule) DefaultConfig

func (m *SessionModule) DefaultConfig() config.Map

DefaultConfig for this module

func (*SessionModule) Inject

func (m *SessionModule) Inject(config *struct {
	// session config is optional to allow usage of the DefaultConfig
	Backend  string `inject:"config:session.backend"`
	Secret   string `inject:"config:session.secret"`
	FileName string `inject:"config:session.file"`
	Secure   bool   `inject:"config:session.cookie.secure"`
	// float64 is used due to the injection as config from json - int is not possible on this
	StoreLength          float64 `inject:"config:session.store.length"`
	MaxAge               float64 `inject:"config:session.max.age"`
	Path                 string  `inject:"config:session.cookie.path"`
	RedisHost            string  `inject:"config:session.redis.host"`
	RedisPassword        string  `inject:"config:session.redis.password"`
	RedisIdleConnections float64 `inject:"config:session.redis.idle.connections"`
	RedisMaxAge          float64 `inject:"config:session.redis.maxAge"`
})

Inject dependencies

type ShutdownEvent

type ShutdownEvent struct{}

ShutdownEvent is dispatched on shutdown

type StartupEvent

type StartupEvent struct{}

StartupEvent is dispatched on startup

type StdLogger

type StdLogger struct {
	log.Logger
}

StdLogger uses the go stdlib logger for logging

func (*StdLogger) Debug

func (l *StdLogger) Debug(args ...interface{})

Debug logs output

func (*StdLogger) Debugf

func (l *StdLogger) Debugf(f string, args ...interface{})

Debugf outputs the formatted debug string

func (*StdLogger) Error

func (l *StdLogger) Error(args ...interface{})

Error log

func (*StdLogger) Flush

func (l *StdLogger) Flush()

Flush does nothing

func (*StdLogger) Info

func (l *StdLogger) Info(args ...interface{})

Info log output

func (*StdLogger) Warn

func (l *StdLogger) Warn(args ...interface{})

Warn log output

func (*StdLogger) WithContext

func (l *StdLogger) WithContext(ctx context.Context) Logger

WithContext currently does nothing

func (*StdLogger) WithField

func (l *StdLogger) WithField(key LogKey, value interface{}) Logger

WithField currently logs the field

func (*StdLogger) WithFields

func (l *StdLogger) WithFields(fields map[LogKey]interface{}) Logger

WithFields currently logs the fields

type TemplateEngine

type TemplateEngine interface {
	Render(context context.Context, name string, data interface{}) (io.Reader, error)
}

TemplateEngine defines the basic template engine

type TemplateFunc

type TemplateFunc interface {
	Func(ctx context.Context) interface{}
}

TemplateFunc defines an interface for a custom function to be used in gotemplates/pug templates

Jump to

Keyboard shortcuts

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