Skip to content

A minimal HTTP/1.1 server implemented from scratch using raw TCP sockets

Notifications You must be signed in to change notification settings

amitdevv/http-from-scratch

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 

Repository files navigation

HTTP Server From Scratch

A minimal HTTP/1.1 server implementation in Go without using any HTTP libraries. Built to understand HTTP at the byte level.

What This Is

Raw TCP server that speaks HTTP. No net/http, no frameworks. Just sockets and bytes.

Run

go run main.go

Server listens on localhost:8080.

Test

curl http://localhost:8080
# Returns: Hello, World!

How It Works

1. TCP Listener

listener, err := net.Listen("tcp", ":8080")

Binds to port 8080. OS queues incoming connections.

2. Accept Connections

conn, err := listener.Accept()

Blocks until client connects. TCP 3-way handshake (SYN, SYN-ACK, ACK) happens here.

3. Read Request

buffer := make([]byte, 1024)
n, _ := conn.Read(buffer)

HTTP request arrives as plain text:

GET / HTTP/1.1\r\n
Host: localhost:8080\r\n
User-Agent: curl/8.15.0\r\n
\r\n

4. Send Response

response := "HTTP/1.1 200 OK\r\n" +
           "Content-Length: 13\r\n" +
           "\r\n" +
           "Hello, World!"
conn.Write([]byte(response))

HTTP Protocol Basics

Request Format

METHOD PATH VERSION\r\n
Header-Name: Header-Value\r\n
Another-Header: Value\r\n
\r\n
[optional body]

Response Format

VERSION STATUS_CODE STATUS_TEXT\r\n
Header-Name: Header-Value\r\n
\r\n
[body]

Key Points

  • Every line ends with \r\n (CRLF)
  • Empty line (\r\n) separates headers from body
  • Content-Length header specifies body size in bytes
  • HTTP is text-based protocol over TCP

About

A minimal HTTP/1.1 server implemented from scratch using raw TCP sockets

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages