I want to return an object as an HTTP response where one of its fields is nullable. The problem is proto3 won't let me do it easily. This happens because I parsed a pointer of string to a string, so when the pointer points to null it produces this error
runtime error: invalid memory address or nil pointer dereference
I have attempted to solve this by at least these two work-arounds I learned from the Internet.
exercise.proto (the message definition)
message ExercisesData {
string Serial = 1 [json_name="serial"];
string Title = 2 [json_name="title"];
oneof OptionalSubmissionSerial {
string SubmissionSerial = 3 [json_name="submission_serial"];
}
mapper.go (to parse a Go struct to fit the proto message)
exercise := &Exercise.ExercisesData {
Serial: e.Serial,
Title: e.Title,
OptionalSubmissionSerial: &Exercise.ExercisesData_SubmissionSerial{
SubmissionSerial: *e.SubmissionInfo.LatestSubmissionSerial,
},
}
exercise.proto (the message definition)
import "google/protobuf/wrappers.proto";
message ExercisesData {
string Serial = 1 [json_name="serial"];
string Title = 2 [json_name="title"];
google.protobuf.StringValue SubmissionSerial = 3 [json_name="submission_serial"];
}
mapper.go (to parse a Go struct to fit the proto message)
exercise := &Exercise.ExercisesData {
Serial: e.Serial,
Title: e.Title,
SubmissionSerial: &wrappers.StringValue{
Value: *e.SubmissionInfo.LatestSubmissionSerial,
},
}
Both ways still produce the same error message, the only difference is the line of code it refers to. That's why I am so helpless. The expected HTTP response would look like this
{
"status": "success",
"data": [
{
"serial": "EXC-NT2OBHQT",
"title": "Title of Topic Exercise",
"submission_serial": null
}
]
}
I really hope anyone can help me to find a way to define a nullable field in proto3 for a Http response and how to parse it from a struct. Thank you!
turns out I find another workaround that actually works! It's using google/protobuf/wrappers.proto but I gotta tweak it a lil' bit in the mapper. Here's how it goes:
import "google/protobuf/wrappers.proto";
message ExercisesData {
string Serial = 1 [json_name="serial"];
string Title = 2 [json_name="title"];
google.protobuf.StringValue SubmissionSerial = 3 [json_name="submission_serial"];
}
import "github.com/golang/protobuf/ptypes/wrappers"
exercise := &pbExercise.GetExercisesData{
Serial: e.Serial,
Title: e.Title,
}
if e.SubmissionInfo.LatestSubmissionSerial != nil {
exercise.SubmissionSerial = &wrappers.StringValue{
Value: *e.LatestSubmissionSerial,
}
}