From 2e48d3ddd01d3375201e464ead0146fa73376406 Mon Sep 17 00:00:00 2001 From: Niccolo Borgioli Date: Fri, 24 May 2024 23:55:58 +0200 Subject: [PATCH] url path --- app/server.go | 84 ++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 83 insertions(+), 1 deletion(-) diff --git a/app/server.go b/app/server.go index e2e6f44..8ab43a6 100644 --- a/app/server.go +++ b/app/server.go @@ -2,13 +2,95 @@ package main import ( "fmt" + "log" + "strings" + // Uncomment this block to pass the first stage "net" "os" ) +const ( + HTTPDelimiter = "\r\n" +) + +type Header struct { + Name string + Value string +} +type Request struct { + Method string + Path string + Version string + Body string + Headers []Header +} + +type HttpResponse struct { + Code uint + Message string +} + +var ( + BadRequest = HttpResponse{Code: 400, Message: "Bad Response"} + NotFound = HttpResponse{Code: 404, Message: "Not Found"} + OK = HttpResponse{Code: 200, Message: "OK"} +) + +// func BadRequest(conn net.Conn) { +// fmt.Fprintf(conn, "HTTP/1.1 400 Bad Request%s%s", HTTPDelimiter, HTTPDelimiter) +// } + +func Respond(conn net.Conn, response HttpResponse) { + fmt.Fprintf(conn, "HTTP/1.1 %d %s%s%s", response.Code, response.Message, HTTPDelimiter, HTTPDelimiter) +} + func handleConnection(conn net.Conn) { - fmt.Fprintf(conn, "HTTP/1.1 200 OK\r\n\r\n") + defer conn.Close() + buffer := make([]byte, 1024) + n, err := conn.Read(buffer) + if err != nil { + log.Fatal(err) + } + + contents := string(buffer[:n]) + parts := strings.Split(contents, HTTPDelimiter) + request := Request{} + isBody := false + for i, part := range parts { + if i == 0 { + head := strings.Split(part, " ") + if len(head) != 3 { + Respond(conn, BadRequest) + return + } + request.Method = head[0] + request.Path = head[1] + request.Version = head[2] + continue + } + + if isBody { + request.Body = part + break + } + + // Headers + if part == "" { + isBody = true + continue + } + h := strings.SplitN(part, ": ", 2) + header := Header{Name: h[0], Value: h[1]} + request.Headers = append(request.Headers, header) + } + fmt.Println(request) + + if request.Path == "/" { + Respond(conn, OK) + return + } + Respond(conn, NotFound) } func main() {