protoc-gen-gotemplate icon indicating copy to clipboard operation
protoc-gen-gotemplate copied to clipboard

helpers: retrieve fields that are used as path variables

Open mgenov opened this issue 4 years ago • 1 comments

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
}

mgenov avatar Jan 04 '21 10:01 mgenov

very needed feature

vtolstov avatar Jan 04 '21 10:01 vtolstov