Reputation: 612
I have written the following code according to the Google "Publishing messages to topics" Guide:
import (
"context"
"fmt"
"io"
"cloud.google.com/go/pubsub"
)
func publishMessage(w io.Writer, projectID, topicID) error {
msg := `{
"source":"test_source",
"data": {
"jobId": "123",
"recordCount": 10000
}
}`
ctx := context.Background()
client, err := pubsub.NewClient(ctx, projectID)
if err != nil {
return fmt.Errorf("pubsub.NewClient: %v", err)
}
t := client.Topic(topicID)
result := t.Publish(ctx, &pubsub.Message{Data: []byte(msg)})
id, err := result.Get(ctx)
if err != nil {
return fmt.Errorf("Get: %v", err)
}
fmt.Fprintf(w, "Published a message; msg ID: %v\n", id)
return nil
}
But each time I receive the error in logs of my Cloud Function:
"com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: expected BEGIN_OBJECT, but was STRING"
I'd be grateful if you have any ideas on how to fix that.
The subscription delivery type: push
Cloud Function Trigger: Topic
Upvotes: 0
Views: 5663
Reputation: 76649
This isn't really a Go question, but rather a NodeJS question. Despite the question is completely missing the Cloud Function's code, I still can tell what is wrong with it: Since you are pushing string instead of JSON, you have to use JSON.parse(string);
before being able to use GSON on it.
If you want a Go answer, you'd probably need to push JSON, to begin with.
In Go one can encode JSON with json.Marshal()
(data object
could be defined as struct
):
type Message struct {
source string
data object
}
msg := Message{ ... }
payload, err := json.Marshal(msg)
It doesn't really matter on which end you'd fix the problem created by pushing a JSON string instead of a JSON. The second one approach might probably be a tad better than the first one (in terms of already providing the expected format, instead of messing around later on). This is based upon, that a JSON and a JSON string are not the same thing (not even with identical content).
Upvotes: 1