【Protobuf】解析protobuf里面的enum

需求
数据传输使用的是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"}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容