美文网首页
【Protobuf】解析protobuf里面的enum

【Protobuf】解析protobuf里面的enum

作者: 冉小妹Ran | 来源:发表于2020-03-27 17:46 被阅读0次

需求
数据传输使用的是proto,API返回的结果是解析过的json。
proto中有enum类型,要求返回的结果中显示enum的字符串值而不是int32值。

错误代码
test.proto

syntax = "proto3";

package protobuf;

enum Level {
    WARNING = 0;
    FATAL = 1;
    SEVERE = 2;
}

message Http {
    string message = 1;
    Level level = 2;
}

p.go

package protobuf

import (
    "encoding/json"
    "net/http"
)

func P() {
    http.HandleFunc(("/"), p)
    http.ListenAndServe(":8080", nil)
}

func p(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    result := Http{Message: "result", Level: Level(1)}
    w.Header().Set("content-type", "application/json")
    json.NewEncoder(w).Encode(result)
}

输出结果

{"message":"result","level":1}

输出的结果是不符合需求的。需求要求输出的结果level应该为1对应的FATAL,然而实际输出的结果是1。
经过研究,发现了错误的地方。

改正方法
将p.go中,func p的最后一句解析result的代码换成

import  "github.com/golang/protobuf/jsonpb"

(&jsonpb.Marshaler{OrigName: true}).Marshal(w, &result)

改正之后便会得到期望的结果。

{"message":"result","level":"FATAL"}

相关文章

  • 【Protobuf】解析protobuf里面的enum

    需求数据传输使用的是proto,API返回的结果是解析过的json。proto中有enum类型,要求返回的结果中显...

  • Protobuf的Enum枚举类型不能同名?

    Protobuf的Enum枚举类型不能同名? 报错 原因 protobuf使用类似c的枚举规则,不允许枚举中出现同...

  • 深入 ProtoBuf - 序列化源码解析

    在上一篇 深入 ProtoBuf - 编码 中,我们详细解析了 ProtoBuf 的编码原理。 有了这个知识储备,...

  • google的protobuf使用

    针对数据解析,个人觉得json,xml等比protobuf 效率低,最近看了下goole的protobuf,发现c...

  • how to use protobuf Reflection?

    最近工作中,需要做一些消息动态解析,因为使用的 protobuf,考虑使用protobuf的反射特性。 1 ref...

  • mac上安装Protobuf

    为什么要安装protobuf 什么是protobuf 怎么判断有没有安装过protobuf? 安装protobuf...

  • protobuf使用

    protobuf的使用 protobuf .proto文件 idea安装protobuf插件 syntax = ...

  • Google Protocol Buffers 数据交换协议

    protobuf 简介 protobuf是什么 protobuf(Protocol Buffers)是Google...

  • protobuf

    protobuf是什么#### protobuf是"Protocol Buffers"的简称。protobuf是一...

  • ulua-pbc

    pbc 它是云风大神早期的一个对protobuf的解析库,相对于protobuf_lua_gen来说,不需要生成巨...

网友评论

      本文标题:【Protobuf】解析protobuf里面的enum

      本文链接:https://www.haomeiwen.com/subject/ptxruhtx.html