refactor reading http request

This commit is contained in:
xvzc 2024-08-15 02:39:23 +09:00
parent bdc1a68691
commit e57f95c604

View File

@ -54,14 +54,11 @@ type HttpPacket struct {
} }
func ReadHttpPacket(rdr io.Reader) (*HttpPacket, error) { func ReadHttpPacket(rdr io.Reader) (*HttpPacket, error) {
sb := strings.Builder{} p, err := parse(rdr)
tee := io.TeeReader(rdr, &sb)
p := &HttpPacket{}
err := parse(p, bufio.NewReader(tee))
if err != nil { if err != nil {
return nil, err return nil, err
} }
p.raw = []byte(sb.String())
return p, nil return p, nil
} }
@ -124,12 +121,17 @@ func (p *HttpPacket) Tidy() {
p.raw = []byte(result) p.raw = []byte(result)
} }
func parse(p *HttpPacket, reader *bufio.Reader) error { func parse(rdr io.Reader) (*HttpPacket, error) {
request, err := http.ReadRequest(reader) sb := strings.Builder{}
tee := io.TeeReader(rdr, &sb)
request, err := http.ReadRequest(bufio.NewReader(tee))
if err != nil { if err != nil {
return err return nil, err
} }
p := &HttpPacket{}
p.raw = []byte(sb.String())
p.domain, p.port, err = net.SplitHostPort(request.Host) p.domain, p.port, err = net.SplitHostPort(request.Host)
if err != nil { if err != nil {
p.domain = request.Host p.domain = request.Host
@ -152,5 +154,5 @@ func parse(p *HttpPacket, reader *bufio.Reader) error {
} }
request.Body.Close() request.Body.Close()
return nil return p, nil
} }