Skip to content

Instantly share code, notes, and snippets.

@jbw
Created November 29, 2022 11:21
Show Gist options
  • Save jbw/6dd4f6f9e67fec80ae00fe4203e8314e to your computer and use it in GitHub Desktop.
Save jbw/6dd4f6f9e67fec80ae00fe4203e8314e to your computer and use it in GitHub Desktop.
Basic 1 to 1 command handler separation example
package command_handler_pattern
import (
"reflect"
)
type NotificationHandler[TNotification any] interface {
Handle(notification TNotification) error
}
var notificationHandlers map[string]interface{} = make(map[string]interface{})
func RegisterNotificationHandler[TNotification any](notification TNotification, handler NotificationHandler[TNotification]) {
notificationHandlers[typeOf(notification).Name()] = handler
}
func Send[T any](request T) {
t := reflect.TypeOf(request).Name()
handler := notificationHandlers[t]
handlerValue := handler.(NotificationHandler[T])
handlerValue.Handle(request)
}
func typeOf(v interface{}) reflect.Type {
return reflect.TypeOf(v)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment