-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
98 lines (84 loc) · 2.08 KB
/
main.go
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main
import (
"fmt"
"io"
"net"
"os"
"strings"
"golang.org/x/net/html"
)
func handleConnection(conn net.Conn) {
defer conn.Close()
// Read from the connection using a fixed size buffer
buffer := make([]byte, 4096)
n, err := conn.Read(buffer)
if err != nil {
fmt.Printf("Error reading: %s\n", err)
return
}
// Convert buffer to string and parse it manually
request := string(buffer[:n])
lines := strings.Split(request, "\r\n")
if len(lines) < 1 {
fmt.Println("Received malformed request")
return
}
// Basic parsing of the request line
parts := strings.Split(lines[0], " ")
if len(parts) < 2 {
fmt.Println("Malformed request line")
return
}
method, urlPath := parts[0], parts[1]
// Handle only GET requests for "/"
if urlPath == "/" && method == "GET" {
htmlFile, err := os.Open("index.html")
if err != nil {
fmt.Printf("Error opening HTML file: %s\n", err)
conn.Write([]byte("HTTP/1.1 500 Internal Server Error\r\n\r\n"))
return
}
defer htmlFile.Close()
// Send the HTTP response header first
header := "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"
conn.Write([]byte(header))
// Use html tokenizer to read the HTML file and write its tokens
z := html.NewTokenizer(htmlFile)
for {
tt := z.Next()
switch tt {
case html.ErrorToken:
// End of file or an error.
if err != nil && err != io.EOF {
fmt.Printf("Error tokenizing HTML: %s\n", err)
}
return
default:
// Get the token and write it to the connection
token := z.Token()
conn.Write([]byte(token.String()))
}
}
} else {
// If the request path is not recognized or the method is not GET
conn.Write([]byte("HTTP/1.1 404 Not Found\r\n\r\n"))
}
}
func main() {
listener, err := net.Listen("tcp", ":8080")
net.Get("http://localhost:8080/")
if err != nil {
fmt.Println("Error listening:", err.Error())
return
}
defer listener.Close()
fmt.Println("Server listening on port 8080")
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println("Error accepting:", err.Error())
return
}
go handleConnection(conn)
}
}