2 回答

TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
我最終傳遞了我正在解組的對(duì)象。
obj := new(GRPCResponse)
assertHTTPResponseOK[*GRPCResponse](t, ctx, "some-endpoint", obj)
func assertHTTPResponseOK[T protoreflect.ProtoMessage](t *testing.T, ctx context.Context, endpoint string, object T) {
body, err := GetResponse(endpoint)
require.Nil(t, err)
err = protojson.Unmarshal(body, object)
require.Nil(t, err)
}

TA貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超8個(gè)贊
這是一個(gè)泛型友好的原型解組器,它避免傳遞第二個(gè)類型,代價(jià)是反射調(diào)用以查看指針內(nèi)部的類型并調(diào)用它的構(gòu)造函數(shù)。
var msg T // Constrained to proto.Message
// Peek the type inside T (as T= *SomeProtoMsgType)
msgType := reflect.TypeOf(msg).Elem()
// Make a new one, and throw it back into T
msg = reflect.New(msgType).Interface().(T)
errUnmarshal := proto.Unmarshal(body, msg)
- 2 回答
- 0 關(guān)注
- 168 瀏覽
添加回答
舉報(bào)