Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set X-User-Agent in gRPC-Web clients #572

Merged
merged 1 commit into from
Aug 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions connect_ext_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2020,6 +2020,31 @@ func TestAllowCustomUserAgent(t *testing.T) {
}
}

func TestWebXUserAgent(t *testing.T) {
t.Parallel()

mux := http.NewServeMux()
mux.Handle(pingv1connect.NewPingServiceHandler(&pluggablePingServer{
ping: func(_ context.Context, req *connect.Request[pingv1.PingRequest]) (*connect.Response[pingv1.PingResponse], error) {
agent := req.Header().Get("User-Agent")
assert.NotZero(t, agent)
assert.Equal(
t,
req.Header().Get("X-User-Agent"),
agent,
)
return connect.NewResponse(&pingv1.PingResponse{Number: req.Msg.Number}), nil
},
}))
server := httptest.NewServer(mux)
t.Cleanup(server.Close)

client := pingv1connect.NewPingServiceClient(server.Client(), server.URL, connect.WithGRPCWeb())
req := connect.NewRequest(&pingv1.PingRequest{Number: 42})
_, err := client.Ping(context.Background(), req)
assert.Nil(t, err)
}

func TestBidiOverHTTP1(t *testing.T) {
t.Parallel()
mux := http.NewServeMux()
Expand Down
9 changes: 9 additions & 0 deletions protocol_grpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ const (
grpcWebContentTypeDefault = "application/grpc-web"
grpcContentTypePrefix = grpcContentTypeDefault + "+"
grpcWebContentTypePrefix = grpcWebContentTypeDefault + "+"

headerXUserAgent = "X-User-Agent"
)

var (
Expand Down Expand Up @@ -252,6 +254,13 @@ func (g *grpcClient) WriteRequestHeader(_ StreamType, header http.Header) {
if getHeaderCanonical(header, headerUserAgent) == "" {
header[headerUserAgent] = []string{defaultGrpcUserAgent}
}
if g.web && getHeaderCanonical(header, headerXUserAgent) == "" {
// The gRPC-Web pseudo-specification seems to require X-User-Agent rather
// than User-Agent for all clients, even if they're not browser-based. This
// is very odd for a backend client, so we'll split the difference and set
// both.
header[headerXUserAgent] = []string{defaultGrpcUserAgent}
}
header[headerContentType] = []string{grpcContentTypeFromCodecName(g.web, g.Codec.Name())}
// gRPC handles compression on a per-message basis, so we don't want to
// compress the whole stream. By default, http.Client will ask the server
Expand Down