I want to make a http proxy gadget using go:
func main() {
listener, err := net.Listen("tcp", ":8080")
if err != nil {
log.Panic(err)
}
for {
client, err := listener.Accept()
if err != nil {
log.Panic(err)
}
go handleClientRequest(client)
}
}
func handleClientRequest(client net.Conn) {
if client == nil {
return
}
defer client.Close()
var buf [1024]byte
n, err := client.Read(buf[:])
if err != nil {
log.Println(err)
return
}
fmt.Println("recv msg:", string(buf[0:n]))
}
1024 bytes may not be enough, there must be an end mark, right?
TCP protocol releases the connection by sending FIN packet, so the FIN packet is the end mark, which means that it is received until the connection is disconnected.
But
So how to judge the end after turning on Keep-Alive?
In fact, the HTTP header has content-length, which is the length of the HTTP packet body
Of course, there is also a case where there is no content-length, that is, chunked encoding is used. The data is divided into a series of blocks and sent, and each block has a size description. Even if the server does not know the size of the entire entity when generating the header (usually because the entity is generated dynamically), chunked encoding can still be used to transmit a number of chunks of known size.
In addition, the HTTP message header and message body are separated by CRLF (carriage return and line feed),
rnrn