response body

This commit is contained in:
Niccolo Borgioli 2024-05-25 00:22:42 +02:00
parent 2e48d3ddd0
commit 77e886b8f9
No known key found for this signature in database
GPG Key ID: 4897ACD13A65977C

View File

@ -3,6 +3,8 @@ package main
import ( import (
"fmt" "fmt"
"log" "log"
"regexp"
"strconv"
"strings" "strings"
// Uncomment this block to pass the first stage // Uncomment this block to pass the first stage
@ -26,23 +28,40 @@ type Request struct {
Headers []Header Headers []Header
} }
type HttpResponse struct { type HttpCode struct {
Code uint Code uint
Message string Message string
} }
var ( var (
BadRequest = HttpResponse{Code: 400, Message: "Bad Response"} BadRequest = HttpCode{Code: 400, Message: "Bad Response"}
NotFound = HttpResponse{Code: 404, Message: "Not Found"} NotFound = HttpCode{Code: 404, Message: "Not Found"}
OK = HttpResponse{Code: 200, Message: "OK"} OK = HttpCode{Code: 200, Message: "OK"}
) )
// func BadRequest(conn net.Conn) { type Response struct {
// fmt.Fprintf(conn, "HTTP/1.1 400 Bad Request%s%s", HTTPDelimiter, HTTPDelimiter) Code HttpCode
// } Version string
Body string
Headers []Header
}
func Respond(conn net.Conn, response HttpResponse) { func Respond(conn net.Conn, response Response) {
fmt.Fprintf(conn, "HTTP/1.1 %d %s%s%s", response.Code, response.Message, HTTPDelimiter, HTTPDelimiter) fmt.Fprintf(conn, "%s %d %s%s", response.Version, response.Code.Code, response.Code.Message, HTTPDelimiter)
bodySize := len(response.Body)
if bodySize > 0 {
response.Headers = append(response.Headers, Header{Name: "Content-Length", Value: strconv.Itoa(bodySize)})
}
for _, header := range response.Headers {
fmt.Fprintf(conn, "%s: %s%s", header.Name, header.Value, HTTPDelimiter)
}
fmt.Fprint(conn, HTTPDelimiter)
if bodySize > 0 {
fmt.Fprint(conn, response.Body)
}
// fmt.Fprintf(conn, "HTTP/1.1 %d %s%s%s", response.Code, response.Message, HTTPDelimiter, HTTPDelimiter)
} }
func handleConnection(conn net.Conn) { func handleConnection(conn net.Conn) {
@ -61,7 +80,7 @@ func handleConnection(conn net.Conn) {
if i == 0 { if i == 0 {
head := strings.Split(part, " ") head := strings.Split(part, " ")
if len(head) != 3 { if len(head) != 3 {
Respond(conn, BadRequest) Respond(conn, Response{Version: "HTTP/1.1", Code: BadRequest})
return return
} }
request.Method = head[0] request.Method = head[0]
@ -87,10 +106,18 @@ func handleConnection(conn net.Conn) {
fmt.Println(request) fmt.Println(request)
if request.Path == "/" { if request.Path == "/" {
Respond(conn, OK) Respond(conn, Response{Version: request.Version, Code: OK})
return return
} }
Respond(conn, NotFound)
re := regexp.MustCompile(`^/echo/([A-Za-z]+)$`)
matches := re.FindStringSubmatch(request.Path)
if len(matches) > 0 {
Respond(conn, Response{Version: request.Version, Code: OK, Body: matches[1]})
return
}
Respond(conn, Response{Version: request.Version, Code: NotFound})
} }
func main() { func main() {