Skip to content

Commit

Permalink
fixed: always drain eventual request body.
Browse files Browse the repository at this point in the history
It seems it is necessary to drain the request body in some situations when using http/2 otherwise it can cause stream errors.

See golang/go#26338
  • Loading branch information
primalmotion committed Mar 9, 2020
1 parent 9949a92 commit 9ada40a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
16 changes: 16 additions & 0 deletions handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ package bahamut
import (
"context"
"fmt"
"io"
"io/ioutil"
"net/http"
"runtime/debug"

Expand Down Expand Up @@ -146,6 +148,20 @@ func handleEventualPanic(ctx context.Context, c chan error, disablePanicRecovery

func runDispatcher(ctx *bcontext, r *elemental.Response, d func() error, disablePanicRecovery bool, marshallers map[elemental.Identity]CustomMarshaller) *elemental.Response {

defer func() {

// It seems it is necessary to drain the request body
// in some situations when using http/2 otherwise it can cause stream errors.
// See https://github.com/golang/go/issues/26338 and associated issues.

if ctx.Request() == nil || ctx.Request().HTTPRequest() == nil {
return
}

_, _ = io.Copy(ioutil.Discard, ctx.Request().HTTPRequest().Body)
_ = ctx.Request().HTTPRequest().Body.Close() // nolint
}()

e := make(chan error)

go func() {
Expand Down
11 changes: 10 additions & 1 deletion handlers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
package bahamut

import (
"bytes"
"context"
"fmt"
"net/http"
Expand Down Expand Up @@ -468,13 +469,21 @@ func TestHandlers_runDispatcher(t *testing.T) {

calledCounter := &counter{}

hreq, err := http.NewRequest(http.MethodGet, "https://127.0.0.1/list", bytes.NewBuffer([]byte("hello")))
if err != nil {
panic(err)
}
gctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
defer cancel()

ctx := newContext(context.Background(), elemental.NewRequest())
ctx.request = elemental.NewRequest()
ctx.ctx = gctx

ctx.request, err = elemental.NewRequestFromHTTPRequest(hreq, testmodel.Manager())
if err != nil {
panic(err)
}

response := elemental.NewResponse(elemental.NewRequest())

d := func() error {
Expand Down

0 comments on commit 9ada40a

Please sign in to comment.