I've created an API in Go that, upon being called, performs a query, creates an instance of a struct, and then encodes that struct as JSON before sending back to the caller. I'd now like to allow the caller to be able to select the specific fields they would like returned by passing in a "fields" GET parameter.
这意味着根据字段值的不同,我的 struct 会发生变化.有什么方法可以从 struct 中删除字段吗?或者至少将它们动态地隐藏在JSON响应中?(注意:有时我的值为空,因此JSON omitEmpty标记在这里不起作用)如果这两个都不可能,有没有更好的处理方法的建议?
A smaller version of the structs I'm using are below:
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)