卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章34126本站已运行391

如何从 golang 中导入的包接收的结构中删除某些项目?

如何从 golang 中导入的包接收的结构中删除某些项目?

问题内容

我从导入的第三方模块的包中收到一个项目:

myitem := importpackage.get()

它是一个像这样的结构:

type importedstruct struct {
    ip                  net.ip                  `json:"ip"`
    index               uint32                  `json:"index"`
    localindex          uint32                  `json:"localindex"`
    remoteindex         []*udp.addr             `json:"remoteindex"`
    certificates        *certificates           `json:"certificates"`
    vpnaddress          []iputil.vpnip          `json:"vpnaddress"`
}

我想删除其中的一项或多项,然后再从我的 golang gin api 以 json 形式返回:

c.json(200, &myitem)

问题是试图找到最有效的资源利用方式来做到这一点。

我考虑了一个循环并将我需要的字段写入一个新结构:

newitem := make([]importedstruct, len(myitem))

i := 0
for _, v := range myitem {
    newitem[i] = ...
    ...
}

c.json(200, &hostlist)

我还考虑过编组,然后解组以将其分配给另一个结构,然后再通过 api 返回它:

// Marshal the host map to json
marshaledJson, err := json.Marshal(newItem)
if err != nil {
    log.Error(err)
    c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
    return
}

// Unmarshal the json into structs
var unmarshalledJson []ImportedStruct
err = json.Unmarshal(marshaledJson, &unmarshalledJson)
if err != nil {
    log.Error(err)
    c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
    return
}

// Return the modified host map
c.JSON(200, &unmarshalledJson)

我希望找到一种更有效的方法来做到这一点。 myitem 可能包含超过 300 万行 json,并循环遍历所有内容,或者编组和解组似乎涉及更多进程,然后只需要实现相对简单的东西即可。

编辑:该结构是一个切片 ([])。


正确答案


定义一个新结构,它是您现有结构的副本,并带有不同的标签:

type importedstructmarshal struct {
    ip                  net.ip                  `json:"ip"`
    index               uint32                  `json:"index"`
    localindex          uint32                  `json:"-"`
    remoteindex         []*udp.addr             `json:"remoteindex"`
    certificates        *certificates           `json:"certificates"`
    vpnaddress          []iputil.vpnip          `json:"vpnaddress"`
}

然后,使用这个新结构来编组:

var input ImportedStruct
forMarshal:=ImportedStructMarshal(input)
...

只要新结构与导入的结构逐个字段兼容,这就会起作用。

卓越飞翔博客
上一篇: Go中如何获取interface{}的值? (接口转换:interface{}是Resp,不是mapinterface{})
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏