将额外字段分配给struct的最佳方法是什么,并且当从[]字节对其进行编码时,所有它都引用子结构,并且此字段不是解组[]字节的一部分?

让我举例说明......

  • 我们有几个结构:
type Update struct {
        UpdateID int32 `json:"update_id"`
        Message *Message `json:"message,omitempty"`
        ...
    }

    type Message struct {
        MessageID int32 `json:"message_id"`
        From *User `json:"from,omitempty"`
        Date int32 `json:"date"`
        Chat Chat `json:"chat"`
        ...
    }
  • 我们的核心结构是APIClient,它有很多方法可以发送内容或获取内容(API包装器)
type API struct {
        Token string
        PollInt int32
        URL string

        client *http.Client
    }

    func(a *API) ... () {

    }

    func(a *API) ... () {

    }

    ...
  • 主循环轮询器发出http请求并返回json响应为"res" - [] byte,因此我们可以使用json.Unmarshal将其映射到特殊的Update结构
func (a *API) GetUpdates(ctx context.Context, gu *GetUpdates) ([]Update, error) {
        buf := bytes.Buffer{}
        err := json.NewEncoder(&buf).Encode(gu)
        if err != nil {
            return nil, fmt.Errorf("getupdates: %s", err)
        }

        res, err := a.DoRequest(&ctx, "getUpdates", &buf)
        if err != nil {
            return nil, fmt.Errorf("getupdates: %s", err)
        }

        var result []Update
        err = json.Unmarshal(res.Result, &result)
        if err != nil {
            return nil, fmt.Errorf("getupdates: %s", err)
        }

        return result, nil
    }
  • 使用json.Unmarshal时,是否可以在非合作链中为所有其他字段扩展所有结构
type Update struct {
        UpdateID int32 `json:"update_id"`
        Message *Message `json:"message,omitempty"`
        ...

        API `json:"-"`
    }

    type Message struct {
        MessageID int32 `json:"message_id"`
        From *User `json:"from,omitempty"`
        Date int32 `json:"date"`
        Chat Chat `json:"chat"`
        ...

        API `json:"-"`
    }

所以我们可以这样做:

var result []Update
    err = json.Unmarshal(res.Result, &result, api)
    if err != nil {
        return nil, fmt.Errorf("getupdates: %s", err)
    }

然后使用它:

result[0].RejectUpdate()
    result[0].Message.SendReply()
    ...
    func (u *Update) RejectUpdate(cause string) {
      m.API.SendMessage(u.Chat.ID, text)
      m.API.Reject(u.ID, cause)
    }
    func (m *Message) SendReply(text string) {
      m.API.SendMessage(m.Chat.ID, text)
    }

所有结构都将通过api(嵌入式结构)扩展到解组...

我对解决方案的看法:

  • 补丁标准编码/ json库 - 不是一个好的选择

  • 获取自定义编码库并重写一点 - 有问题的选择

  • 手动解组所有对象 - 可怕的代码

type Bot struct {
        superCLient string
    }

    type Image struct {
        Name string
        Path string

        *Bot `json:"-"`
    }

    type FormFile struct {
        Img  *Image
        Name string

        *Bot `json:"-"`
    }

    func main() {
        data := []byte(`{"Img": {"Name": "Vi", "Path": "/etc/log"}, "Name": "Josh"}`)
        bot := &Bot{
            superCLient: "ClientExample",
        }
        var omg FormFile
        omg.CustomUnmarshal(data, bot)
        fmt.Println(omg)
    }

    func (ff *FormFile) CustomUnmarshal(data []byte, bot *Bot) error {
        var f map[string]*json.RawMessage
        json.Unmarshal(data, &f)

        var i Image
        i.CustomUnmarshal(*f["Img"], bot)
        ff.Img = &i

        json.Unmarshal(*f["Name"], ff.Name)

        ff.Bot = bot

        return nil
    }

    func (img *Image) CustomUnmarshal(data []byte, bot *Bot) error {
        err := json.Unmarshal(data, img)
        img.Bot = bot
        return err
    }