-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
49 lines (40 loc) · 758 Bytes
/
main.go
File metadata and controls
49 lines (40 loc) · 758 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package main
import (
"fmt"
"net"
)
func main() {
listener, err := net.Listen("tcp", ":8080")
if err != nil {
fmt.Println("Error:", err)
return
}
defer listener.Close()
fmt.Println("Server listening on :8080")
for {
conn, err := listener.Accept()
if err != nil {
continue
}
handleConnection(conn)
}
}
func handleConnection(conn net.Conn) {
defer conn.Close()
// Read HTTP request
buffer := make([]byte, 1024)
n, _ := conn.Read(buffer)
fmt.Printf("\nReceived:\n%s\n", buffer[:n])
// Send HTTP response
body := "Hello, World!"
response := fmt.Sprintf(
"HTTP/1.1 200 OK\r\n"+
"Content-Length: %d\r\n"+
"\r\n"+
"%s",
len(body),
body,
)
conn.Write([]byte(response))
fmt.Printf("Sent:\n%s\n", response)
}