This is a creation in Article, where the information may have evolved or changed.
To the new unit finally a little idle, and then Daoteng http. Previous articles can be referenced by: TCP sockets, HTTP requests via Golang, and TCP sockets via Golang, which simulates the request (cont.).
Before it was a client of research, let's look at the server. The HTTP authoritative guide has a very simple perl
server for development, and I'll write it with a big one Golang
. The HTTP protocol is a transport-layer-based TCP protocol that listens on port 80. Simple to write (I will not be complex), is the simplest TCP listening, receiving messages, processing and return. I am referring to the "Go Socket Programming Practice: TCP Server and client implementation". The main logic is this:
ln, err := net.Listen("tcp", fmt.Sprintf("%s:%d", "", *portFlag))defer ln.Close()if err != nil {panic(err)}log.Printf("<<<Server Accepting on Port %d>>>\n\n", *portFlag)for {conn, err := ln.Accept()if err != nil {log.Panicln(err)}go handleConnection(conn)}
I do things like from the simplest start, one is because I will not much, one is simple to himself can understand, later maintenance is actually more convenient.
Return to the point, this piece actually from the time of the study of the old write, minutes to fix. Then there is the HTTP protocol thing. Of course, it's the simplest. HTTP is divided into three parts: the start line, the header (header), and the body (body).
The starting line is only one row, which is the protocol version and the status code, to the CRLF
end, that is, the \r\n
head, the contents of the head is the key value pairs, each set of key value pairs to the CRLF
end; the head and the main body, but also need one more CRLF
, I guess is to parse the content convenient. Not required after the subject CRLF
.
is the detailed request format. Where SP
is the space.
Some necessary head (because I found that if not, the request will fail), that is, Content-Type
and Content-length
. Content-length is the length of the body.
func handleConnection(conn net.Conn) {defer conn.Close()log.Printf("[%s]<<<Request From %s>>>\n", time.Now().String(), conn.RemoteAddr())serve_time := time.Now()buffers := bytes.Buffer{}buffers.WriteString("HTTP/1.1 200 OK\r\n")buffers.WriteString("Server: Cyeam\r\n")buffers.WriteString("Date: " + serve_time.Format(time.RFC1123) + "\r\n")buffers.WriteString("Content-Type: text/html; charset=utf-8\r\n")buffers.WriteString("Content-length:" + fmt.Sprintf("%d", len(DEFAULT_HTML)) + "\r\n")buffers.WriteString("\r\n")buffers.WriteString(DEFAULT_HTML)conn.Write(buffers.Bytes())}
Finally add a little, connect remember to close
Reference documents
- "1" http authoritative guide
- "2" James f.kurose, Keith w.ross.computer NETWORKING. A Top-down approach featuring the Internet (third Edition).
- "3" NETWORKING INFO BLOG. HTTP Message Format.