Skip to content

Commit

Permalink
Add test342: PubSub Go - Not works on GAE standard
Browse files Browse the repository at this point in the history
The pubsub library is unsupported on GAE standard:

googleapis/google-cloud-go#702

Maybe I should try Python...
  • Loading branch information
snsinfu committed Apr 1, 2018
1 parent eb889e6 commit 5dc3a7f
Show file tree
Hide file tree
Showing 3 changed files with 101 additions and 0 deletions.
12 changes: 12 additions & 0 deletions test342-gae_cron_pubsub/app.yaml
@@ -0,0 +1,12 @@
runtime: go
api_version: go1

handlers:
- url: /topics
script: _go_app
secure: always

- url: /publish/.*
script: _go_app
login: admin
secure: always
4 changes: 4 additions & 0 deletions test342-gae_cron_pubsub/cron.yaml
@@ -0,0 +1,4 @@
cron:
- description: periodic event
url: /publish/periodic-1min
schedule: every 1 minutes
85 changes: 85 additions & 0 deletions test342-gae_cron_pubsub/main.go
@@ -0,0 +1,85 @@
package main

import (
"fmt"
"net/http"
"time"

"cloud.google.com/go/pubsub"
"github.com/go-chi/chi"
"google.golang.org/api/iterator"
"google.golang.org/appengine"
"google.golang.org/appengine/log"
)

// The pubsub library does not work!
// https://github.com/GoogleCloudPlatform/google-cloud-go/issues/702

func main() {
r := chi.NewRouter()
r.Get("/topics", handleTopics)
r.Get("/publish/{topic}", handlePublish)
http.Handle("/", r)
appengine.Main()
}

func handleTopics(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)

client, err := pubsub.NewClient(ctx, appengine.AppID(ctx))
if err != nil {
log.Errorf(ctx, "Failed to create client: %s", err)
http.Error(w, "", http.StatusInternalServerError)
return
}
defer client.Close()

w.WriteHeader(http.StatusOK)

it := client.Topics(ctx)
for {
t, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
log.Errorf(ctx, "Failed to list topics: %s", err)
return
}
fmt.Fprintln(w, t)
}
}

func handlePublish(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)

client, err := pubsub.NewClient(ctx, appengine.AppID(ctx))
if err != nil {
log.Errorf(ctx, "Failed to create client: %s", err)
http.Error(w, "", http.StatusInternalServerError)
return
}
defer client.Close()

name := chi.URLParam(r, "topic")
topic := client.Topic(name)

topic.PublishSettings = pubsub.PublishSettings{
DelayThreshold: 100 * time.Millisecond,
CountThreshold: 1,
ByteThreshold: 1e6,
NumGoroutines: 1,
Timeout: 1 * time.Second,
}

msg := pubsub.Message{
Data: []byte(name),
}
if _, err := topic.Publish(ctx, &msg).Get(ctx); err != nil {
log.Errorf(ctx, "Failed to publish message: %s", err)
http.Error(w, "", http.StatusInternalServerError)
return
}

w.WriteHeader(http.StatusOK)
}

0 comments on commit 5dc3a7f

Please sign in to comment.