sam
sam

Reputation: 787

Input validation of enum in proto request

My proto file has enum defined. Here's an example

package mypackage;

enum Direction {
    EAST = 1;
    WEST = 2;
    NORTH = 3;
    SOUTH = 4;
}

message SomeActionRequest {
    Direction direction = 1;
}

service SomeService {
    rpc SomeAction (SomeActionRequest) returns (...) { }
}

In the implementation of my service method (SomeAction), what is the best way to validate that the input enum value (direction) is a valid enum?

Upvotes: 2

Views: 2869

Answers (2)

Brits
Brits

Reputation: 18345

The generated code will contain a map which can be useful for validating (perhaps not the most efficient method but simple and does not need to be updated when the enum changes). For example:

enum Direction {
  UNKNOWN_DIRECTION = 0;
  EAST = 1;
  WEST = 2;
  NORTH = 3;
  SOUTH = 4;
}

will generate :

var (
    Direction_name = map[int32]string{
        0: "UNKNOWN_DIRECTION",
        1: "EAST",
        2: "WEST",
        3: "NORTH",
        4: "SOUTH",
    }...

So you can use something like (I have added a zero value to make this valid).

if input == Direction_UNKNOWN_DIRECTION {
   // missing value
} else if _, ok := Direction_name[input]; !ok {
   /// Not a valid value
}

Here is a sample in the playground.

Upvotes: 2

Tinwor
Tinwor

Reputation: 7973

If the values are sequential without interruption (e.g. 1, 2, 3, 4 and not 1, 3, 6, 7), you can create a function to check that the enum value is in a range.
Something like:

func isValid(value int) {
  return value >= int(Direction. EAST) && value <= int(DIRECTION.SOUTH)
}

Upvotes: 0

Related Questions