0

我正在使用微框架开发我的新项目,并且我已经完成了 GRPC 工作。但是现在,我需要编写与前端交互的网关。我真的不想写重复的代码,我在pb.go文件中找到了一些代码。

代码定义了一些结构和初始化函数。如下所示:

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")
}


同时,我发现这篇文章有没有办法从字符串创建结构的实例?.

幸运的是。pb 文件已经为我定义了它,但是 protoc 自动生成文件定义为 nil 指针(*AuthLoginReq)(nil)

api.go

        qiniuType := proto.MessageType("device.info.provider.service.AuthLoginReq")

        pbValue := reflect.New(qiniuType)

        pbStruct := pbValue.Elem().Interface()

当我改变 pbSturct 并没有真正改变,因为是 nil 指针

ctx.ShouldBind(&pbStruct)

pbStruct已经是变化了。但pbValue不是改变。

我该如何改变pbValue

4

1 回答 1

0

我不是很熟悉,reflect知道这是不可能的,但如何做到这一点绝对不明显。您可能会发现设置自己的注册表会更容易:

    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

于 2019-09-03T02:17:09.173 回答