hub: Use sync to use read and write locks for map with active subscriptions

master
Elis Hirwing 2 years ago
parent 3e145a7b41
commit bde2eb067e
Signed by: etu
GPG Key ID: D57EFA625C9A925F
  1. 25
      hub/main.go

@ -12,6 +12,7 @@ import (
"net/http"
"net/url"
"strings"
"sync"
"github.com/gorilla/mux"
)
@ -29,11 +30,18 @@ type MovieResponse struct {
ImdbRating float64 `json:"imdb_rating"`
}
var subscriptions map[string]Subscriber
var subscriptions struct {
sync.RWMutex
subscriptions map[string]Subscriber
}
func main() {
router := mux.NewRouter()
subscriptions = make(map[string]Subscriber)
subscriptions = struct {
sync.RWMutex
subscriptions map[string]Subscriber
}{subscriptions: make(map[string]Subscriber)}
router.HandleFunc("/", subscribeHandler).Methods("POST")
router.HandleFunc("/spam/{topic}", publishToAll)
@ -83,12 +91,14 @@ func subscribeHandler(w http.ResponseWriter, r *http.Request) {
log.Printf("Created subscription for %s", hubTopic)
// Make a subscription and store it
subscriptions[hubCallback.String()] = Subscriber{
subscriptions.Lock()
subscriptions.subscriptions[hubCallback.String()] = Subscriber{
URL: hubCallback.String(),
Topic: hubTopic,
Secret: hubSecret,
LeaseSeconds: hubLeaseSeconds,
}
subscriptions.Unlock()
return
}
@ -110,8 +120,13 @@ func publishToAll(w http.ResponseWriter, r *http.Request) {
ImdbRating: 7.4,
}
if len(subscriptions) > 0 {
for _, subscriber := range subscriptions {
// Claim lock, defer unlock and copy current subscriptions
subscriptions.RLock()
defer subscriptions.RUnlock()
subs := subscriptions.subscriptions
if len(subs) > 0 {
for _, subscriber := range subs {
// Skip this subscripber if it's the wrong topic
if topic != subscriber.Topic {
continue

Loading…
Cancel
Save