我在Go语言中创建了一个API,当被调用时会执行查询操作、创建一个结构体实例,并将该结构体编码为JSON后发送回调用方。现在,我希望允许调用方通过传递“fields”GET参数来选择他们想要返回的特定字段。
这意味着根据字段值,我的结构体会发生改变。有没有办法从结构体中删除字段?或者至少动态地在JSON响应中隐藏它们?(注意:有时候我有空值,因此JSON omitEmpty标签在这里不起作用)如果这两种方法都不可行,那么是否有更好的处理方法建议?
我正在使用的结构体的较小版本如下:
type SearchResult struct {
Date string `json:"date"`
IdCompany int `json:"idCompany"`
Company string `json:"company"`
IdIndustry interface{} `json:"idIndustry"`
Industry string `json:"industry"`
IdContinent interface{} `json:"idContinent"`
Continent string `json:"continent"`
IdCountry interface{} `json:"idCountry"`
Country string `json:"country"`
IdState interface{} `json:"idState"`
State string `json:"state"`
IdCity interface{} `json:"idCity"`
City string `json:"city"`
} //SearchResult
type SearchResults struct {
NumberResults int `json:"numberResults"`
Results []SearchResult `json:"results"`
} //type SearchResults
我然后这样对响应进行编码并输出:err := json.NewEncoder(c.ResponseWriter).Encode(&msg)