codecrafters-http-server-go/app/server.go

70 lines
1.4 KiB
Go
Raw Normal View History

2024-05-24 22:03:55 +02:00
package main
import (
"fmt"
2024-05-25 11:51:11 +02:00
"net"
"os"
2024-05-24 22:03:55 +02:00
)
2024-05-25 18:27:53 +02:00
// type Handler = func(req Request, res Response)
// type Middleware = func(next Handler) Handler
// var m Middleware = func(next Handler) Handler {
// return func(req Request, res Response) {
// fmt.Println("Start")
// next(req, res)
// fmt.Println("End")
// }
// }
2024-05-25 11:51:11 +02:00
func handleConnection(conn net.Conn, routes Routes) {
2024-05-24 23:55:58 +02:00
defer conn.Close()
2024-05-25 12:11:36 +02:00
2024-05-25 18:27:53 +02:00
req, ok := parseRequest(conn)
2024-05-25 12:31:01 +02:00
if !ok {
2024-05-25 18:27:53 +02:00
Respond(conn, req, Response{Version: "HTTP/1.1", Code: BadRequest})
2024-05-25 12:31:01 +02:00
return
2024-05-24 23:55:58 +02:00
}
2024-05-25 18:27:53 +02:00
fmt.Println(req)
2024-05-24 23:55:58 +02:00
2024-05-25 11:51:11 +02:00
for _, route := range routes.stringRoutes {
2024-05-25 18:27:53 +02:00
if req.Path == route.path && req.Method == route.method {
Respond(conn, req, route.handler(req))
2024-05-25 00:29:26 +02:00
return
}
}
2024-05-25 11:51:11 +02:00
for _, route := range routes.regexpRoutes {
2024-05-25 18:27:53 +02:00
if req.Method != route.method {
2024-05-25 11:51:11 +02:00
continue
2024-05-25 00:45:53 +02:00
}
2024-05-25 18:27:53 +02:00
if matches := route.regex.FindStringSubmatch(req.Path); len(matches) > 0 {
Respond(conn, req, route.handler(req, matches))
2024-05-25 00:49:48 +02:00
return
}
2024-05-25 00:45:53 +02:00
}
2024-05-25 18:27:53 +02:00
Respond(conn, req, Response{Version: req.Version, Code: NotFound})
2024-05-24 22:56:28 +02:00
}
2024-05-24 22:03:55 +02:00
func main() {
fmt.Println("Logs from your program will appear here!")
2024-05-24 22:46:34 +02:00
l, err := net.Listen("tcp", "0.0.0.0:4221")
if err != nil {
fmt.Println("Failed to bind to port 4221")
os.Exit(1)
}
2024-05-24 22:56:28 +02:00
for {
conn, err := l.Accept()
if err != nil {
fmt.Println("Error accepting connection: ", err.Error())
os.Exit(1)
}
2024-05-25 11:51:11 +02:00
go handleConnection(conn, routes)
2024-05-24 22:46:34 +02:00
}
2024-05-24 22:56:28 +02:00
2024-05-24 22:03:55 +02:00
}