JohnGB
JohnGB

Reputation: 2016

How best to send complex data with FCM / GCM using Go

Both the FCM and GCM documentation give the structure of the data payload as a map[string]string (although google's GCM package implements it at a map[string]interface{})

However, there are many cases where a simple flat key:value structure doesn't meet the needs of an application. Some examples are when a slice of values is needed, or when another non-trivial struct needs to be sent.

What would be the cleanest way of sending more complicated data structures as a map[string]string?


Conclusion: I have marked the answer by fl0cke as correct given that it provides a solution to sending complex data with FCM / GCM using Go. However, it is clear from the FCM documentation, that the intention is for the data to be key:value string pairs moving forward, and so to be sure that nothing gets broken in the future, I will be sticking to simple key:value string pairs.

Upvotes: 3

Views: 1531

Answers (1)

fl0cke
fl0cke

Reputation: 2884

According to this answer, it is possible to send nested data with FCM/GCM. To do that, you can write your own FCM Client or fork google's implementation and change the type definition of Data from

type Data map[string]interface{}

to

type Data interface{}

And plug in any type that is JSON serializable (e.g. nested structs).


It is also possible to send the data via a JSON string without changing the type definition of Data:

// first marshal your complex data structure
complexData := someComplexStruct{...}
b, _ := json.Marshal(complexData)

// then assign the returned json string to one key of your choice
data := map[string]interface{}{"key":string(b)}

You probably have to unquote the json string before parsing it on the client.

Upvotes: 2

Related Questions