Home > Software design >  Go Struct to decode expo push notification response?
Go Struct to decode expo push notification response?

Time:03-25

I am making a service in go that sends push notification to Expo Backend. Once the http call is made Expo respond with bellow format(according to Expo):

{
  "data": [
    {
      "status": "error" | "ok",
      "id": string, // this is the Receipt ID
      // if status === "error"
      "message": string,
      "details": JSON
    },
    ...
  ],
  // only populated if there was an error with the entire request
  "errors": [{
    "code": number,
    "message": string
  }]
}

And here is an provioded example of a response:

{
  "data": [
    {
      "status": "error",
      "message": "\\\"ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]\\\" is not a registered push notification recipient",
      "details": {
        "error": "DeviceNotRegistered"
      }
    },
    {
      "status": "ok",
      "id": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
    }
  ]
}

I created struct to decode the response.Now i get a error try to decode the reponse for the "details" field, No matter what type i use in my Struct. How can i deal with that field that expo mark as "JSON"?

import (
    uuid "github.com/satori/go.uuid"
)


type PushResult struct {
    Errors []ErrorDetails `json:"errors,omitempty"`
    Datas   []DataPart     `json:"data,omitempty"`
}
type ErrorDetails struct {
    Code    int32  `json:"code,omitempty"`
    Message string `json:"message,omitempty"`
}
type DataPart struct {
    Status  string    `json:"status,omitempty"`
    ID      uuid.UUID `json:"id,omitempty"`
    Message string    `json:"message,omitempty"`
    Details string `json:"details,omitempty"` //also tried map[string]string and interface{}

}

This is the struct i am using. i also tried this by looking at the example:

type DataPart struct {
    Status  string    `json:"status,omitempty"`
    ID      uuid.UUID `json:"id,omitempty"`
    Message string    `json:"message,omitempty"`
    Details struct{
           Error string `json:"error"`} `json:"details,omitempty"` 

}

But every time get an error like "json: cannot unmarshal object into Go struct field DataPart.data.details"

CodePudding user response:

I just created you struct using your response exemple and it worked completly fine.

Playground

That said if you wana a better way of debugging an "unmarshal error" you can unwrap it. That way you can print aditional data.

var t *json.UnmarshalTypeError
if errors.As(err, &t) {
    spew.Dump(t)
}

Example -> I changed the error type to integer so I can fake the error.

OBS: Note that your "Datas" is an array and only the 1st one have an error.

  • Related