解决protobuf忽略空返回值的问题

最近在用Kratos开发项目的时候遇到了问题,repeated类型的字段在值为空的情况下,字段被直接忽略掉了。

我希望的是即使为空的情况下也能返回一个空数组,而不是直接把整个字段忽略掉,就像下面这样:

{
    "code": 0,
    "msg": "",
    "result": {
        "id": 2,
        "memberCount": 13,
        "name": "超级团队",
        "admin": [
            {
                "id": 4,
                "name": "Jason(Jason)"
            },
        ],
        "clientCamp": []
    }
}

经过多方排查之后找到了问题所在,google会在生成pb.go文件时在json标签里插入omitempty属性,而json库在转换json时一旦遇到这个标签就会忽略掉空字段,这不符合我的需求,所以把这个字段去掉就好了。

先写一个shell脚本来递归遍历api目录下的pb.go文件:

#!/bin/bash

function scandir() {
    local cur_dir parent_dir workdir
    workdir=$1
    cd $workdir
    if [ [$workdir = "/"] ]
    then
        cur_dir=""
    else
        cur_dir=$(pwd)
    fi 
    for dirlist in $(ls $cur_dir)
    do
        if test -d $dirlist; then
            cd $dirlist
            scandir ${cur_dir}/${dirlist}
            cd ..
        elif [ "${dirlist#*.}"x = "pb.go"x ];then
            echo ${cur_dir}/${dirlist}
        fi
    done
}

if test -d $1
then
    scandir $1
elif test -f $1
then
    echo "you input a file but not a directory, pls reinput and try again"
    exit 1
else
    echo "the Directory isn't exist which you input. pls input a new one"
    exit1
fi

接着修改Makefile文件:

.PHONY: api
# generate api proto
api:
    protoc --proto_path=./api \
           --proto_path=./third_party \
           --go_out=paths=source_relative:./api \
           --go-http_out=paths=source_relative:./api \
           --go-grpc_out=paths=source_relative:./api \
           --openapi_out==paths=source_relative:. \
           $(API_PROTO_FILES)
    ./scandir.sh api | xargs -n1 -IX bash -c 'sed s/,omitempty// X > X.tmp'
    ./scandir.sh api | xargs -n1 -IX bash -c 'mv X{.tmp,}'

在api的最下面添加替换脚本,流程就是遍历scandir脚本查出来的pb.go文件,替换掉文件里所有的omitempty,然后将文件暂存为.tmp,最后再覆盖原文件。

今后每次执行make api时就会连带自动替换掉所有生成文件中的omitempty,免得每次手动替换麻烦又容易出错。

参考:https://ld246.com/article/1591110788411

你可能感兴趣的:(解决protobuf忽略空返回值的问题)