Skip to content

Commit 02e4576

Browse files
committed
Add option for setting bufio.Scanner buffer
This commit adds a Proxy option that lets the user set a custom buffer for the bufio.Scanner used for reading the response body. This allows users to workaround 'token too long' errors when reading responses that have tokens larger than the default buffer size.
1 parent 0ad062e commit 02e4576

File tree

1 file changed

+24
-6
lines changed

1 file changed

+24
-6
lines changed

wsproxy/websocket_proxy.go

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,13 @@ type RequestMutatorFunc func(incoming *http.Request, outgoing *http.Request) *ht
2727

2828
// Proxy provides websocket transport upgrade to compatible endpoints.
2929
type Proxy struct {
30-
h http.Handler
31-
logger Logger
32-
methodOverrideParam string
33-
tokenCookieName string
34-
requestMutator RequestMutatorFunc
35-
headerForwarder func(header string) bool
30+
h http.Handler
31+
logger Logger
32+
maxRespBodyBufferBytes int
33+
methodOverrideParam string
34+
tokenCookieName string
35+
requestMutator RequestMutatorFunc
36+
headerForwarder func(header string) bool
3637
}
3738

3839
// Logger collects log messages.
@@ -52,6 +53,15 @@ func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
5253
// Option allows customization of the proxy.
5354
type Option func(*Proxy)
5455

56+
// WithMaxRespBodyBufferSize allows specification of a custom size for the
57+
// buffer used while reading the response body. By default, the bufio.Scanner
58+
// used to read the response body sets the maximum token size to MaxScanTokenSize.
59+
func WithMaxRespBodyBufferSize(nBytes int) Option {
60+
return func(p *Proxy) {
61+
p.maxRespBodyBufferBytes = nBytes
62+
}
63+
}
64+
5565
// WithMethodParamOverride allows specification of the special http parameter that is used in the proxied streaming request.
5666
func WithMethodParamOverride(param string) Option {
5767
return func(p *Proxy) {
@@ -234,6 +244,14 @@ func (p *Proxy) proxy(w http.ResponseWriter, r *http.Request) {
234244
}()
235245
// write loop -- take messages from response and write to websocket
236246
scanner := bufio.NewScanner(responseBodyR)
247+
248+
// if maxRespBodyBufferSize has been specified, use custom buffer for scanner
249+
var scannerBuf []byte
250+
if p.maxRespBodyBufferBytes > 0 {
251+
scannerBuf = make([]byte, 0, 64*1024)
252+
scanner.Buffer(scannerBuf, p.maxRespBodyBufferBytes)
253+
}
254+
237255
for scanner.Scan() {
238256
if len(scanner.Bytes()) == 0 {
239257
p.logger.Warnln("[write] empty scan", scanner.Err())

0 commit comments

Comments
 (0)