I'm using micro framework to develop my new project, and I have finished the GRPC work. But now, I need to write the gateway to interacting with the frontend. I don't really want to write repetitive code, and I find some code in pb.go
file.
the code is defined some struct and init function. like below:
type AuthLoginReq struct {
Username string `protobuf:"bytes,1,opt,name=username,proto3" json:"username,omitempty"`
Password string `protobuf:"bytes,2,opt,name=password,proto3" json:"password,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func init() {
proto.RegisterType((*AuthLoginReq)(nil), "device.info.provider.service.AuthLoginReq")
}
Meanwhile, I found this article is there a way to create an instance of a struct from a string?.
Fortunately. pb file already defines it for me, but protoc auto generate file is defined nil pointer (*AuthLoginReq)(nil)
.
api.go
qiniuType := proto.MessageType("device.info.provider.service.AuthLoginReq")
pbValue := reflect.New(qiniuType)
pbStruct := pbValue.Elem().Interface()
When I change pbSturct is not really change, because is nil pointer
ctx.ShouldBind(&pbStruct)
pbStruct
is already change. but pbValue
is not change.
How do I change pbValue
?
I'm not super familiar with reflect
enough to know that it's impossible, but it's definitely not obvious how to do it. You might find that setting up your own registry will be easier:
registry := map[string]func() interface{}{
"AuthLoginReq": func() interface{} {
return &AuthLoginReq{}
},
}
i := registry["AuthLoginReq"]()
a := i.(*AuthLoginReq)
a.Username = "root"
fmt.Printf("%#v
", a)