Skip to content

Commit

Permalink
grpc-ecosystem#4238 Added the WithWriteContentLength ServerMuxOption,…
Browse files Browse the repository at this point in the history
… which if set will write a Content-Length header before calling w.Write on non-streaming responses
  • Loading branch information
joshgarnett committed Apr 22, 2024
1 parent c6fd361 commit f6081f3
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
5 changes: 5 additions & 0 deletions runtime/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"io"
"net/http"
"net/textproto"
"strconv"
"strings"

"google.golang.org/genproto/googleapis/api/httpbody"
Expand Down Expand Up @@ -176,6 +177,10 @@ func ForwardResponseMessage(ctx context.Context, mux *ServeMux, marshaler Marsha
return
}

if mux.writeContentLength {
w.Header().Set("Content-Length", strconv.Itoa(len(buf)))
}

if _, err = w.Write(buf); err != nil {
grpclog.Infof("Failed to write response: %v", err)
}
Expand Down
8 changes: 8 additions & 0 deletions runtime/mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ type ServeMux struct {
routingErrorHandler RoutingErrorHandlerFunc
disablePathLengthFallback bool
unescapingMode UnescapingMode
writeContentLength bool
}

// ServeMuxOption is an option that can be given to a ServeMux on construction.
Expand Down Expand Up @@ -224,6 +225,13 @@ func WithDisablePathLengthFallback() ServeMuxOption {
}
}

// WithWriteContentLength returns a ServeMuxOption to enable writing content length on non-streaming responses
func WithWriteContentLength() ServeMuxOption {
return func(serveMux *ServeMux) {
serveMux.writeContentLength = true
}
}

// WithHealthEndpointAt returns a ServeMuxOption that will add an endpoint to the created ServeMux at the path specified by endpointPath.
// When called the handler will forward the request to the upstream grpc service health check (defined in the
// gRPC Health Checking Protocol).
Expand Down

0 comments on commit f6081f3

Please sign in to comment.