zeromicro / go-zero

A cloud-native Go microservices framework with cli tool for productivity.
https://go-zero.dev
MIT License
29.4k stars 3.97k forks source link

How can I set custom http headers in RPC service? #4466

Open zebra-min opened 5 days ago

zebra-min commented 5 days ago

In our project, we used gRpc-Gateway. But I find, I can't set http header in RPC response. What should we do? Thanks!

kevwan commented 4 days ago

grpc-gateway or go-zero gateway?

zebra-min commented 3 days ago

I'm not sure. I learn it from this doc "https://go-zero.dev/en/docs/tutorials/gateway/grpc".

gateway.go main code follow:

import (
    "github.com/zeromicro/go-zero/core/conf"
    "github.com/zeromicro/go-zero/gateway"
    "github.com/zeromicro/go-zero/rest/httpx"
    "github.com/zeromicro/go-zero/zrpc"
    "google.golang.org/grpc/status"
)

func main() {
    flag.Parse()

    logx.DisableStat()

    var c config.Config
    conf.MustLoad(*configFile, &c)
    gw := gateway.MustNewServer(c.Gateway)
    sessionRpcClient := sessionservice.NewSessionService(zrpc.MustNewClient(c.Session))

    gw.Use(middleware.SessionMiddleware(sessionRpcClient))
    gw.Use(middleware.AuthMiddleware)

    defer gw.Stop()

    // 设置错误处理
    httpx.SetErrorHandlerCtx(grpcErrorHandlerCtx)
    fmt.Printf("Starting rpc server at %d...\n", c.Gateway.Port)
    gw.Start()
}
kesonan commented 3 days ago

It's need to pull a new request to append the http headers into context metadata.