moul / protoc-gen-gotemplate

:open_file_folder: generic protocol generator based on golang's text/template (grpc/protobuf)
https://manfred.life/protoc-gen-gotemplate
MIT License
438 stars 70 forks source link

helpers: retrieve fields that are used as path variables #171

Open mgenov opened 3 years ago

mgenov commented 3 years ago

Is your feature request related to a problem? Please describe. It would be really use-full if templates are able to iterate over fields used as path variables.

Describe the solution you'd like Here is a sample snippet that better describes the intention. By adding this function as helper the template will be able to list only fields used as variables and may reduce the generated code.

func urlVariableFields(path string, d *ggdescriptor.Message) []*descriptor.FieldDescriptorProto {
    vars := []*descriptor.FieldDescriptorProto{}
    for _, field := range d.Field {
        if !isFieldMessage(field) {
            if strings.Contains(path, fmt.Sprintf("{%s}", *field.Name)) {
                vars = append(vars, field)
                continue
            }
            // JSON name field is checked as fallback. The value set by the protocol compiler.
            // If the user has set a "json_name" option on a field, that option's value
            // will be used in this check. By default value in this property will be field name in
            // camelCase format.
            if strings.Contains(path, fmt.Sprintf("{%s}", *field.JsonName)) {
                vars = append(vars, field)
            }
        }
    }
    return vars
}
vtolstov commented 3 years ago

very needed feature