// publishUpdate notifies Pub/Sub subscribers that the book identified with // the given ID has been added/modified. func publishUpdate(bookID int64) { if !bookshelf.PubSubEnabled() { return } pubSubCtx, err := bookshelf.PubSubCtx() if err != nil { log.Print(err) return } b, err := json.Marshal(bookID) if err != nil { return } _, err = pubsub.Publish(pubSubCtx, bookshelf.PubSubTopic, &pubsub.Message{ Data: b, }) log.Printf("Published update to Pub/Sub for Book ID %d: %v", bookID, err) }
func main() { var err error pubSubCtx, err = bookshelf.PubSubCtx() if err != nil { log.Fatal(err) } booksClient, err = books.New(http.DefaultClient) if err != nil { log.Fatalf("could not access Google Books API: %v", err) } // ignore returned errors, which will be "already exists". If they're fatal // errors, then following calls (e.g. in the subscribe function) will also fail. pubsub.CreateTopic(pubSubCtx, bookshelf.PubSubTopic) pubsub.CreateSub(pubSubCtx, subName, bookshelf.PubSubTopic, 0, "") // Start worker goroutine. go subscribe() // [START http] // Publish a count of processed requests to the server homepage. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { countMu.Lock() defer countMu.Unlock() fmt.Fprintf(w, "This worker has processed %d books.", count) }) port := "8080" if p := os.Getenv("PORT"); p != "" { port = p } log.Fatal(http.ListenAndServe(":"+port, nil)) // [END http] }