我从进口第三方模块的包裹中收到了一件物品:
myItem := importedPackage.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
可能包含超过 3m 行的 JSON,并循环遍历它,或者编组和解组似乎涉及更多的过程,然后它只需要实现一些相对简单的东西。
如果可以更改结构,请为 json 标记添加破折号。例如删除
LocalIndex
:
type ImportedStruct 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"`
}
如果你不能改变结构(第 3 方包),并且你对分叉或其他东西不感兴趣,你将不得不制作自己的结构,包括或嵌入
ImportedStruct
。然后,在你的新结构上实现 json.Marshaler
和 json.Unmarshaler
来做你需要它做的事。