Last active
September 29, 2024 11:13
-
-
Save rohan-kiratsata/09124d7291b8cd8aafd23ae24d64fb6e to your computer and use it in GitHub Desktop.
Basic HTTP server from scratch in go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Basic implementation of an HTTP server in Go to learn and understand how it works. | |
What does it NOT do? | |
- improved error handling | |
- parse headers | |
- routing | |
- ...many more | |
*/ | |
package main | |
import ( | |
"bufio" | |
"fmt" | |
"net" | |
"strings" | |
) | |
func main() { | |
// setup tcp listner on port | |
listener, err := net.Listen("tcp", ":8080") | |
if err != nil { | |
fmt.Println("Error starting server:", err) | |
return | |
} | |
defer listener.Close() | |
fmt.Println("Server listening on port 8080...") | |
// continusly checks for new conn. and handles them | |
for { | |
conn, err := listener.Accept() | |
if err != nil { | |
fmt.Println("Error accepting connection:", err) | |
continue | |
} | |
// goroutine : to handle multiple clients req in seperate goroutine, serves simultaneously. | |
go handleConnection(conn) | |
} | |
} | |
func handleConnection(conn net.Conn) { | |
defer conn.Close() | |
reader := bufio.NewReader(conn) | |
requestLine, _ := reader.ReadString('\n') | |
parts := strings.Split(requestLine, " ") | |
if len(parts) < 3 { | |
fmt.Println("Invalid HTTP request") | |
return | |
} | |
method, path, version := parts[0], parts[1], parts[2] | |
fmt.Printf("Received request: %s %s %s", method, path, version) | |
// Read and discard headers | |
for { | |
line, _ := reader.ReadString('\n') | |
if line == "\r\n" { | |
break | |
} | |
} | |
// Send response | |
response := "HTTP/1.1 200 OK\r\n" + | |
"Content-Type: text/plain\r\n" + | |
"Connection: close\r\n" + | |
"\r\n" + | |
"Hello, World!" | |
conn.Write([]byte(response)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment