Search code examples
gogrpc-goprotobuf-go

Go build command throws - panic: interface conversion: interface {} is []uint8, not *validator.FieldValidator


In below Go function I am getting error when I tried to run build command to generate pb.go file. panic: interface conversion: interface {} is []uint8, not *validator.FieldValidator github.com/mygithub/myproject/plugin.getFieldValidatorIfAny(0xc0001d4b60, 0x5b5020)

Any suggestion on how to resolve this

func getFieldValidatorIfAny(field *descriptor.FieldDescriptorProto) *validator.FieldValidator {
    if field.Options != nil {
        v, err := proto.GetExtension(field.Options, validator.E_Field)
        if err == nil && v.(*validator.FieldValidator) != nil {
            return (v.(*validator.FieldValidator))
        }
    }
    return nil
}

I am trying to add validation using from https://github.com/mwitkow/go-proto-validators


Solution

  • Per https://beta.pkg.go.dev/github.com/golang/protobuf/proto#GetExtension (emphasis mine):

    If the descriptor is type complete (i.e., ExtensionDesc.ExtensionType is non-nil), then GetExtension parses the encoded field and returns a Go value of the specified type. If the field is not present, then the default value is returned (if one is specified), otherwise ErrMissingExtension is reported.

    If the descriptor is type incomplete (i.e., ExtensionDesc.ExtensionType is nil), then GetExtension returns the raw encoded bytes for the extension field.

    So, here it appears that validator.E_Field is “type incomplete”. You may need to add a dependency on the package that defines the extension so that its type will be registered — perhaps by using import _ "example.com/some/proto" to link it in to your binary.