Skip to content

Add support for custom struct tags like custom:"name" #234

Open

Description

@andrewbenton

When passing structs to the expr.Env() option, it would be nice to have a way to modify the field extraction behavior to be able to:

  • extract or map names based on tags such as the common json tag
  • ignore non-exported fields
  • ignore methods

In my particular case, I'm working with protobuf-generated structs and using the expr library as a way to implement a filtering grammar similar to what is described in https://google.aip.dev/160.

Here's an example struct:

type MyType struct {
    state protoimpl.MessageState
    sizeCache protoimpl.SizeCache
    unknownFields protoimpl.UnknownFields

    Id         string                 `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
    Name       string                 `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`
    CreateTime *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=create_time,json=createTime,proto3" json:"
}

func (x *MyType) GetId() string {
    if x != nil {
        return x.Id
    }
    return ""
}

/* other generated functions for exported fields */

The above struct results in both the non-exported fields and duplicate methods being made available to the expression context. It also means that the default names in the expression (prior to patching) don't match the names given in the protobuf.

Activity

  1. antonmedv commented on Apr 27, 2022

    @antonmedv
    Member

    Make sense. I'll add it to my todo list :)

  2. antonmedv commented on Nov 5, 2022

    @antonmedv
    Member

    Done!

  3. NickYadance commented on Sep 4, 2025

    @NickYadance

    Done!

    Similar issue but failed to find workaround. So is there any way to refer field by json tag in expr for this protobuf case ?

  4. changed the title [-]Enhance expr.Env() options on structs[/-] [+]Add support for custom struct tags like `custom:"name"`[/+] on Sep 18, 2025
  5. added this to the v1.18.0 milestone on Sep 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions