et-go 20240919重建
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

57 lines
1.3 KiB

package et_rpc
import (
"encoding/json"
"et_rpc/pb"
"fmt"
"google.golang.org/protobuf/proto"
"log"
"testing"
)
// TestProtoJSONConversion 测试 Protobuf 和 JSON 之间的转换
func TestProtoJSONConversion(t *testing.T) {
// 创建请求
request := createHandleDataRequest()
// 序列化请求为 Protobuf 格式
data, err := proto.Marshal(request)
if err != nil {
log.Fatalf("Failed to marshal request: %v", err)
}
// 打印序列化后的数据
fmt.Println("Serialized HandleDataRequest:", data)
// 这里可以将序列化后的数据发送到 gRPC 服务
// 例如:client.HandleIotaData(context.Background(), request)
}
func createJSONData(id string, value float64) (string, error) {
data := map[string]interface{}{
"id": id,
"value": value,
}
jsonData, err := json.Marshal(data)
if err != nil {
return "", err
}
return string(jsonData), nil
}
func createHandleDataRequest() *pb.HandleDataRequest {
request := &pb.HandleDataRequest{}
// 添加 JSON 数据消息
json1, _ := createJSONData("1", 10.5)
json2, _ := createJSONData("2", 20.3)
json3, _ := createJSONData("3", 15.8)
request.Messages = append(request.Messages, json1)
request.Messages = append(request.Messages, json2)
request.Messages = append(request.Messages, json3)
return request
}