Go Struct解码博览会推送通知响应?

Go Struct to decode expo push notification response?

我正在使用 go 服务向 Expo 后端发送推送通知。一旦发起 http 调用,Expo 将以以下格式响应(根据 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
  }]
}

这是提供的响应示例:

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

我创建了结构来解码 response.Now 我在尝试解码“详细信息”字段的响应时遇到错误,无论我在我的结构中使用什么类型。我如何处理世博会标记为“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{}

}

这是我正在使用的结构。我也通过查看示例进行了尝试:

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"` 

}

但每次都会出现类似“json: cannot unmarshal object into Go struct field DataPart.data.details”的错误

我刚刚使用你的响应示例创建了你的结构,它工作得很好。

Playground

也就是说,如果您想要一种更好的调试“解组错误”的方法,您可以将其解包。这样您就可以打印其他数据。

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

Example -> 我将错误类型更改为整数,这样我就可以伪造错误。

OBS:请注意,您的“数据”是一个数组,只有第一个有错误。