build-an-http-server / lesson-06.md
Lesson 06 · Sockets

Answer with a canned response

You can read a request and you can write bytes - today you connect them into a request-response loop that replies to every connection with a fixed 200. It is the first thing a browser will call a working web server.

The goal

Read a request's head, then write a fixed "200 OK" response back to the client.

Start here - the target
TO DO
Scenario: The server responds to a request
Giventhe server receives "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n"
Whenit finishes reading the head
Thenit writes back exactly "HTTP/1.1 200 OK\r\n\r\n"
Background

Reading and writing finally meet: accept a connection, read its head, and send a reply. That reply is still hard-coded — a bare status line and the blank line that marks the end of the head, with no body — but it is a valid HTTP response, and a browser or curl will accept it as a 200.

This is the walking skeleton of the whole server. From here every chapter replaces one hard-coded piece with something real: first the request becomes a parsed structure, then the response becomes something you build from a status, headers, and a body.

Make it work
func handle(conn net.Conn) {
defer conn.Close()
r := bufio.NewReader(conn)
readHead(r) // consume the request so the client's write completes
conn.Write([]byte("HTTP/1.1 200 OK\r\n\r\n"))
}
CheckpointDONE
curl http://localhost:PORT/ now gets a real 200 response from your server. Commit.