package main
import (
"flag"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/gateway"
)
var configFile = flag.String("f", "etc/gateway.yaml", "config file")
func main() {
flag.Parse()
var c gateway.GatewayConf
conf.MustLoad(*configFile, &c)
gw := gateway.MustNewServer(c, withHeaders())
defer gw.Stop()
// 注册错误处理
httpx.SetErrorHandlerCtx(grpcErrorHandlerCtx)
gw.Start()
}
// gateway header 会带上前缀 Grpc-Metadata-, 自定义处理方法, 去掉前缀
func withHeaders() func(*gateway.Server) {
return gateway.WithHeaderProcessor(func(header http.Header) []string {
var values []string
// 这里使用 protobuf 定义枚举的 name 字符串作为 key
for key, _ := range xxx.MetaDataRequiredKey_value {
values = append(values, fmt.Sprintf("%s:%s", key, header.Get(key)))
}
return values
})
}
// 自定义错误
func grpcErrorHandler(err error) (int, any) {
if s, ok := status.FromError(err); ok {
return http.StatusOK, Res{
Code: int(s.Code()),
Msg: s.Message(),
}
}
return http.StatusOK, Res{
Code: http.StatusInternalServerError,
Msg: err.Error(),
}
}
func grpcErrorHandlerCtx(ctx context.Context, err error) (int, any) {
return grpcErrorHandler(err)
}
type Res struct {
Code int `json:"code"`
Msg string `json:"msg"`
}