Senior
Tell about your use of event-driven approach in your example.
sobes.tech AI
Answer from AI
In one of my Go projects, I implemented an event-driven architecture for processing orders in an e-commerce system. The main idea was that when certain events occurred (e.g., order creation, payment, shipment), events were generated that subscribers processed asynchronously.
For this, I used channels and goroutines to separate event generation from processing. For example, when an order was created, an event was sent to a channel, and a separate worker listened to this channel and performed tasks such as notifying the user, updating statistics, etc.
Code example:
package main
import (
"fmt"
"time"
)
type OrderEvent struct {
OrderID string
Type string
}
func eventProducer(events chan<- OrderEvent) {
events <- OrderEvent{OrderID: "12345", Type: "OrderCreated"}
}
func eventConsumer(events <-chan OrderEvent) {
for event := range events {
switch event.Type {
case "OrderCreated":
fmt.Printf("Processing order creation event: %s\n", event.OrderID)
// Additional logic
}
}
}
func main() {
events := make(chan OrderEvent)
go eventConsumer(events)
eventProducer(events)
time.Sleep(time.Second) // Wait for processing
}
This approach makes it easy to scale event processing and add new subscribers without changing the event generator.