Skip to content

golaxo/gofieldselect

Repository files navigation

Go Field Select

version CI PR checks Go Report Card

Warning

GoFieldSelect is under heavy development.

A powerful select query parameter implementation based on Field selection for filtering desired fields in a REST API.

⬇️ Getting Started

To start using it:

go get github.com/golaxo/gofieldselect@latest

And then use it either by

Using Get for each field

n, err := gofieldselect.Parse("name,address(street)")
an, _ := fieldSelection.SelectField("address")

dto := examples.User{
    Name:    gofieldselect.Get(n, "name", user.Name),
    Surname: gofieldselect.Get(n, "surname", user.Surname),
    Age:     gofieldselect.Get(n, "age", user.Age),
    Address: &examples.Address{
        Street: gofieldselect.Get(an.Child, "street", user.Address.Street),
        Number: gofieldselect.Get(an.Child, "number", user.Address.Number),
    },
}

// dto only contains `name` and `address.street` set, the rest of the fields contain the default value.

Check examples/get to see it in action.

Reflection for an existing instance

n, _ := gofieldselect.Parse("name,surname")
src := User{Name: "John", Surname: "Doe", Age: 20}
selected, _ := gofieldselect.GetWithReflection(n, src)
// selected only contains `name` and `surname` set, `age` is set to its default value.

Check examples/getwithreflection to see it in action.

🚀 Features

GoFieldSelect provides a way to return only certain fields. It can be used as a query parameter in your REST endpoints.

Imagine you have the following JSON:

{
  "id": 1,
  "name": "John",
  "address": {
    "street": "Example street",
    "number": "1"
  }
}

Root field selection

JSON selecting some fields: ?fields=id,name:

{
  "id": 1,
  "name": "John"
}

Nested field selection

JSON selecting some fields: ?fields=id,name,address(street):

{
  "id": 1,
  "name": "John",
  "address": {
    "street": "Example street"
  }
}

About

Apply field selection pattern to your REST apis.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 3

  •  
  •  
  •