Removing fields from struct or hiding them in JSON Response

后端 未结 13 1389
孤街浪徒
孤街浪徒 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:23

    I just published sheriff, which transforms structs to a map based on tags annotated on the struct fields. You can then marshal (JSON or others) the generated map. It probably doesn't allow you to only serialize the set of fields the caller requested, but I imagine using a set of groups would allow you to cover most cases. Using groups instead of the fields directly would most likely also increase cache-ability.

    Example:

    package main
    
    import (
        "encoding/json"
        "fmt"
        "log"
    
        "github.com/hashicorp/go-version"
        "github.com/liip/sheriff"
    )
    
    type User struct {
        Username string   `json:"username" groups:"api"`
        Email    string   `json:"email" groups:"personal"`
        Name     string   `json:"name" groups:"api"`
        Roles    []string `json:"roles" groups:"api" since:"2"`
    }
    
    func main() {
        user := User{
            Username: "alice",
            Email:    "alice@example.org",
            Name:     "Alice",
            Roles:    []string{"user", "admin"},
        }
    
        v2, err := version.NewVersion("2.0.0")
        if err != nil {
            log.Panic(err)
        }
    
        o := &sheriff.Options{
            Groups:     []string{"api"},
            ApiVersion: v2,
        }
    
        data, err := sheriff.Marshal(o, user)
        if err != nil {
            log.Panic(err)
        }
    
        output, err := json.MarshalIndent(data, "", "  ")
        if err != nil {
            log.Panic(err)
        }
        fmt.Printf("%s", output)
    }
    

提交回复
热议问题