Skip to content

Instantly share code, notes, and snippets.

@tpiha
Created April 19, 2015 16:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tpiha/0a9ec8644ea400aac83e to your computer and use it in GitHub Desktop.
Save tpiha/0a9ec8644ea400aac83e to your computer and use it in GitHub Desktop.
package workers
type Action interface {
Call(queue string, message *Msg, next func() bool) bool
}
type Middlewares struct {
actions []Action
}
func (m *Middlewares) Append(action Action) {
m.actions = append(m.actions, action)
}
func (m *Middlewares) Prepend(action Action) {
actions := make([]Action, len(m.actions)+1)
actions[0] = action
copy(actions[1:], m.actions)
m.actions = actions
}
func (m *Middlewares) call(queue string, message *Msg, final func()) bool {
return continuation(m.actions, queue, message, final)()
}
func continuation(actions []Action, queue string, message *Msg, final func()) func() bool {
if Running {
return func() (acknowledge bool) {
if len(actions) > 0 {
acknowledge = actions[0].Call(
queue,
message,
continuation(actions[1:], queue, message, final),
)
if !acknowledge {
return
}
} else {
final()
}
return true
}
} else {
return func() (acknowledge bool) {
return false
}
}
}
func NewMiddleware(actions ...Action) *Middlewares {
return &Middlewares{actions}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment