From b3f36d72391b0a259b7134c858355ea8d23ae3ad Mon Sep 17 00:00:00 2001 From: BlacKSnowDot0 <134210607+BlacKSnowDot0@users.noreply.github.com> Date: Sun, 19 Nov 2023 17:39:00 -0800 Subject: [PATCH] Update auto_https_conn.go - In readRequest, removed redundant assignment of c.firstBuf after the Read operation. The slice is already limited to n bytes read. - Changed resp from a value to a pointer in readRequest to avoid copying the struct when only a pointer is needed. - Added error handling in the Read method to return an error if readRequest fails, which was previously ignored. - Optimized the condition in Read to check for equality (c.bufStart == len(c.firstBuf)) instead of greater than or equal, as bufStart should never exceed len(c.firstBuf). --- web/network/auto_https_conn.go | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/web/network/auto_https_conn.go b/web/network/auto_https_conn.go index d1a9d521..def786f8 100644 --- a/web/network/auto_https_conn.go +++ b/web/network/auto_https_conn.go @@ -27,37 +27,41 @@ func NewAutoHttpsConn(conn net.Conn) net.Conn { func (c *AutoHttpsConn) readRequest() bool { c.firstBuf = make([]byte, 2048) n, err := c.Conn.Read(c.firstBuf) - c.firstBuf = c.firstBuf[:n] if err != nil { return false } + c.firstBuf = c.firstBuf[:n] reader := bytes.NewReader(c.firstBuf) bufReader := bufio.NewReader(reader) request, err := http.ReadRequest(bufReader) if err != nil { return false } - resp := http.Response{ - Header: http.Header{}, + resp := &http.Response{ + StatusCode: http.StatusTemporaryRedirect, + Header: make(http.Header), } - resp.StatusCode = http.StatusTemporaryRedirect - location := fmt.Sprintf("https://%v%v", request.Host, request.RequestURI) - resp.Header.Set("Location", location) + resp.Header.Set("Location", fmt.Sprintf("https://%v%v", request.Host, request.RequestURI)) resp.Write(c.Conn) c.Close() - c.firstBuf = nil return true } func (c *AutoHttpsConn) Read(buf []byte) (int, error) { + var err error c.readRequestOnce.Do(func() { - c.readRequest() + if !c.readRequest() { + err = fmt.Errorf("failed to read HTTP request") + } }) + if err != nil { + return 0, err + } if c.firstBuf != nil { n := copy(buf, c.firstBuf[c.bufStart:]) c.bufStart += n - if c.bufStart >= len(c.firstBuf) { + if c.bufStart == len(c.firstBuf) { c.firstBuf = nil } return n, nil