Created
July 14, 2017 22:37
-
-
Save therealplato/9820bb92a5376811918bf78de62e684d to your computer and use it in GitHub Desktop.
event bus pattern in go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// An event BUS is a communication pattern between subsystems | |
// event SOURCING is a design pattern that I would define as: | |
// System state is stored as an append-only sequence of events, | |
// current system state is the result of applying all events in order. | |
// this demonstrates an event bus: | |
package main | |
import ( | |
"fmt" | |
"strconv" | |
"time" | |
) | |
type event interface { | |
Event() string | |
} | |
type eventDeleteEntryRequest struct { | |
userID int | |
entryUUID string | |
} | |
func (e eventDeleteEntryRequest) Event() string { | |
return "DeleteEntryRequest" | |
} | |
type eventDeleteEntry struct { | |
entryUUID string | |
} | |
func (e eventDeleteEntry) Event() string { | |
return "DeleteEntry" | |
} | |
func main() { | |
// A real bus has to multiplex events, ignoring that with ugly channels | |
bus := make(chan event) | |
go endpointService(bus) | |
go authService(bus) | |
go dbService(bus) | |
<-time.After(10 * time.Second) | |
} | |
func endpointService(bus chan event) { | |
var i int | |
for { | |
i++ | |
req := eventDeleteEntryRequest{ | |
userID: i, | |
entryUUID: "covfefe" + strconv.Itoa(i), | |
} | |
fmt.Printf("Publishing %+v\n", req) | |
bus <- req | |
time.Sleep(time.Second) | |
} | |
} | |
func authService(bus chan event) { | |
for e := range bus { | |
f, ok := e.(eventDeleteEntryRequest) | |
if !ok { | |
// put it back | |
bus <- e | |
continue | |
} | |
// auth logic: | |
if f.userID%2 == 0 { | |
// granted | |
g := eventDeleteEntry{ | |
entryUUID: f.entryUUID, | |
} | |
bus <- g | |
} | |
} | |
} | |
func dbService(bus chan event) { | |
for e := range bus { | |
f, ok := e.(eventDeleteEntry) | |
if !ok { | |
// put it back | |
bus <- e | |
continue | |
} | |
// db logic: | |
fmt.Printf("deleting %s\n", f.entryUUID) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment