最近在用Kratos開發(fā)項目的時候遇到了問題放妈,repeated類型的字段在值為空的情況下,字段被直接忽略掉了藐窄。
我希望的是即使為空的情況下也能返回一個空數(shù)組,而不是直接把整個字段忽略掉,就像下面這樣:
{
"code": 0,
"msg": "",
"result": {
"id": 2,
"memberCount": 13,
"name": "超級團(tuán)隊",
"admin": [
{
"id": 4,
"name": "Jason(Jason)"
},
],
"clientCamp": []
}
}
經(jīng)過多方排查之后找到了問題所在,google會在生成pb.go文件時在json標(biāo)簽里插入omitempty
屬性氓鄙,而json庫在轉(zhuǎn)換json時一旦遇到這個標(biāo)簽就會忽略掉空字段,這不符合我的需求业舍,所以把這個字段去掉就好了抖拦。
先寫一個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,最后再覆蓋原文件下面。
今后每次執(zhí)行make api時就會連帶自動替換掉所有生成文件中的omitempty复颈,免得每次手動替換麻煩又容易出錯。