Skip to content

Commit

Permalink
Create main.go
Browse files Browse the repository at this point in the history
Signed-off-by: Kamil Mosciszko <[email protected]>
  • Loading branch information
Raezil authored Feb 20, 2025
1 parent 7911dc7 commit 5b51458
Showing 1 changed file with 68 additions and 0 deletions.
68 changes: 68 additions & 0 deletions examples/2/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package main

import (
"encoding/json"
"fmt"
"log"
"net/http"

gbus "github.com/Raezil/GoEventBus"

"github.com/gorilla/mux"

Check failure on line 11 in examples/2/main.go

View workflow job for this annotation

GitHub Actions / build

no required module provides package github.com/gorilla/mux; to add it:
_ "github.com/lib/pq"
)

// HouseWasSold represents an event for when a house has been sold
type HouseWasSold struct{}

// NewDispatcher initializes the dispatcher with event handlers
func NewDispatcher() *gbus.Dispatcher {
return &gbus.Dispatcher{
HouseWasSold{}: func(m map[string]interface{}) (gbus.Result, error) {
price, ok := m["price"].(int) // Match the correct key "price"
if !ok {
return gbus.Result{}, fmt.Errorf("price not provided or invalid")
}
result := fmt.Sprintf("House was sold for %d", price)
log.Println(result)
return gbus.Result{
Message: result,
}, nil
},
}
}

func main() {
// Initialize dispatcher and event store
dispatcher := NewDispatcher()
eventstore := gbus.NewEventStore(dispatcher)

router := mux.NewRouter()
router.HandleFunc("/house-sold", func(w http.ResponseWriter, r *http.Request) {
// Publish the event with the correct key "price"
eventstore.Publish(gbus.NewEvent(
HouseWasSold{},
map[string]interface{}{
"price": 100,
},
))

// Broadcast the event after publishing, wait for completion
if err := eventstore.Broadcast(); err != nil {
log.Printf("Error broadcasting event: %v", err)
http.Error(w, "Failed to process event", http.StatusInternalServerError)
return
}

// Send response back to client
w.Header().Set("Content-Type", "application/json")
response := map[string]string{"status": "House sold event published"}
json.NewEncoder(w).Encode(response)
})

serverAddress := ":8080"
log.Printf("Server is listening on %s", serverAddress)
if err := http.ListenAndServe(serverAddress, router); err != nil {
log.Fatalf("Failed to start server: %v", err)
}
}

0 comments on commit 5b51458

Please sign in to comment.