登录
首页 >  Golang >  Go问答

浏览会推送通知的Go Struct解码方法

来源:stackoverflow

时间:2024-02-23 10:36:23 143浏览 收藏

Golang不知道大家是否熟悉?今天我将给大家介绍《浏览会推送通知的Go Struct解码方法》,这篇文章主要会讲到等等知识点,如果你在看完本篇文章后,有更好的建议或者发现哪里有问题,希望大家都能积极评论指出,谢谢!希望我们能一起加油进步!

问题内容

我正在 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"
    }
  ]
}

我创建了结构体来解码响应。现在尝试解码“详细信息”字段的响应时出现错误,无论我在结构体中使用什么类型。我该如何处理博览会标记为“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:无法将对象解组到go结构字段datapart.data.details”之类的错误


正确答案


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

Playground

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

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

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

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

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>