0

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?

Papandadj
  • 74
  • 4
  • Take a look at https://github.com/grpc-ecosystem/grpc-gateway. Perhaps you can leverage this project, or get some ideas from it. – sberry Aug 19 '19 at 18:09
  • @sberry This way need to change proto file and Sacrifice flexibility . Maybe I should find answer in micro api . thanks – Papandadj Aug 20 '19 at 00:39

1 Answers1

0

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\n", a)

https://play.golang.org/p/CDIIF69CpUd

Liyan Chang
  • 7,721
  • 3
  • 39
  • 59