package twitchhttp

import (
	"fmt"
	"io"
	"io/ioutil"
)

// maxBytesToReadOnClose ensures up to 512 additional bytes are read after
// closing an http response body to improve connection reuse.
// This value is copied from maxPostHandlerReadBytes in net/http/server.go.
// Source: https://github.com/google/go-github/pull/317
// NOTE: Re-evaluate if this behavior is still needed after Go1.7 is released.
const maxBytesToReadOnClose = 256 << 10

var _ io.ReadCloser = (*readAllOnCloseBody)(nil)

// readAllOnCloseBody wraps an http.Response body and discards the remaining
// http body upon calling Close(), up to maxBytesToReadOnClose.
type readAllOnCloseBody struct {
	body io.ReadCloser
}

func (b *readAllOnCloseBody) Close() error {
	if _, err := io.CopyN(ioutil.Discard, b.body, maxBytesToReadOnClose); err != nil {
		if err != io.EOF {
			return fmt.Errorf("reading remaining bytes on body before close: %v", err)
		}
	}
	return b.body.Close()
}

func (b *readAllOnCloseBody) Read(p []byte) (int, error) {
	return b.body.Read(p)
}
