56 lines
1.1 KiB
Go
56 lines
1.1 KiB
Go
package net_utils
|
|
|
|
import (
|
|
"bufio"
|
|
"io"
|
|
"net"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
/*
|
|
May be useful if you need to download/upload something asyncroniously
|
|
or if needed to use HTTP ontop of some unusual protocol like UNIX Sockets,
|
|
UDP (are u insane?) or QUIC (WTF aren't u using HTTPv3 then?)
|
|
*/
|
|
|
|
// Optimised to read only response codes
|
|
// Reads response codes until getting EOF or error
|
|
func ConnHttpReadRespCodes(conn net.Conn) (codes []int, err error) {
|
|
reader := bufio.NewReader(conn)
|
|
|
|
for {
|
|
var line string
|
|
line, err = reader.ReadString('\n')
|
|
if err != nil && err == io.EOF {
|
|
break
|
|
} else if err != nil {
|
|
return codes, err
|
|
}
|
|
|
|
if strings.HasPrefix(line, "HTTP/") {
|
|
parts := strings.Split(line, " ")
|
|
if len(parts) < 2 {
|
|
continue
|
|
}
|
|
if code, err := strconv.Atoi(parts[1]); err == nil {
|
|
codes = append(codes, code)
|
|
}
|
|
}
|
|
|
|
for {
|
|
line, err := reader.ReadString('\n')
|
|
if err != nil && err == io.EOF {
|
|
return codes, nil
|
|
} else if err != nil {
|
|
return codes, err
|
|
}
|
|
if line == "\r\n" || line == "\n" {
|
|
break // End of headers
|
|
}
|
|
}
|
|
}
|
|
|
|
return codes, err
|
|
}
|