Removing fields from struct or hiding them in JSON Response

后端 未结 13 1343
孤街浪徒
孤街浪徒 2020-12-12 09:37

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

13条回答
  •  有刺的猬
    2020-12-12 10:26

    You can use the reflect package to select the fields that you want by reflecting on the field tags and selecting the json tag values. Define a method on your SearchResults type that selects the fields you want and returns them as a map[string]interface{}, and then marshal that instead of the SearchResults struct itself. Here's an example of how you might define that method:

    func fieldSet(fields ...string) map[string]bool {
        set := make(map[string]bool, len(fields))
        for _, s := range fields {
            set[s] = true
        }
        return set
    }
    
    func (s *SearchResult) SelectFields(fields ...string) map[string]interface{} {
        fs := fieldSet(fields...)
        rt, rv := reflect.TypeOf(*s), reflect.ValueOf(*s)
        out := make(map[string]interface{}, rt.NumField())
        for i := 0; i < rt.NumField(); i++ {
            field := rt.Field(i)
            jsonKey := field.Tag.Get("json")
            if fs[jsonKey] {
                out[jsonKey] = rv.Field(i).Interface()
            }
        }
        return out
    }
    

    and here's a runnable solution that shows how you would call this method and marshal your selection: http://play.golang.org/p/1K9xjQRnO8

提交回复
热议问题