I am interested in the action of web server to http keep-alive header. So I built a simple http server based on http server. The server does nothing but response to the client with a simple html http body.
The code of server is here:
package main
import (
"fmt"
"net"
"os"
)
func main() {
l, err := net.Listen("tcp", "localhost:9765")
if err != nil {
fmt.Println("Error listening:", err.Error())
os.Exit(1)
}
defer l.Close()
for {
conn, err := l.Accept()
fmt.Println("New connection...")
if err != nil {
fmt.Println("Error accepting: ", err.Error())
os.Exit(1)
}
go handleRequest(conn)
}
}
// handler
func handleRequest(conn net.Conn) {
for {
buf := make([]byte, 512)
_, err := conn.Read(buf)
if err != nil {
fmt.Println("Error reading:", err.Error())
conn.Close()
break
}
fmt.Printf("%s", buf)
str := `HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 8
Content-Type: application/javascript
alert(1)
`
conn.Write([]byte(str))
}
}
I added a demo html to local nginx static server:
<head>
<meta charset="UTF-8">
<script type=text/javascript src="test.js"></script>
<script type=text/javascript src="http://localhost:9765/3"></script>
<script type=text/javascript src="http://localhost:9765/2"></script>
<script type=text/javascript src="http://localhost:9765/1"></script>
<script type=text/javascript src="http://localhost:9765/17"></script>
<script type=text/javascript src="http://localhost:9765/16"></script>
<script type=text/javascript src="http://localhost:9765/15"></script>
<script type=text/javascript src="http://localhost:9765/14"></script>
<script type=text/javascript src="http://localhost:9765/13"></script>
<script type=text/javascript src="http://localhost:9765/12"></script>
<script type=text/javascript src="http://localhost:9765/30"></script>
<script type=text/javascript src="http://localhost:9765/29"></script>
<script type=text/javascript src="http://localhost:9765/28"></script>
<script type=text/javascript src="http://localhost:9765/27"></script>
<script type=text/javascript src="http://localhost:9765/26"></script>
<script type=text/javascript src="http://localhost:9765/25"></script>
<script type=text/javascript src="http://localhost:9765/24"></script>
<script type=text/javascript src="http://localhost:9765/23"></script>
<script type=text/javascript src="http://localhost:9765/22></script>
<script type=text/javascript src="http://localhost:9765/21"></script>
</head>
<body>
<h1>loader测试页面</h1>
<span>hello world</span>
</body>
</html>
When visit the file with chrome, I found all response is normal, but tcp connection was closed after every single http request. The TCP got EOF error after sending http response.
If you send the wrong content length in the header, the browser will either hang (waiting for content that will never come) or close the connection (when it sees invalid junk after the content). What else could it do?