From 950dbee8a6b7114ec997efa8a1a070a13cc8a0bb Mon Sep 17 00:00:00 2001 From: Gabriel De Los Rios Date: Mon, 3 Mar 2025 19:35:37 -0300 Subject: [PATCH] feat(server): add http server and req handler --- main.go | 11 +++++++++++ request_handler.go | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 main.go create mode 100644 request_handler.go diff --git a/main.go b/main.go new file mode 100644 index 0000000..9e1bc1a --- /dev/null +++ b/main.go @@ -0,0 +1,11 @@ +package main + +import ( + "net/http" +) + +func main() { + + http.HandleFunc("/", RequestHandler) + http.ListenAndServe(":3333", nil) +} diff --git a/request_handler.go b/request_handler.go new file mode 100644 index 0000000..18b6356 --- /dev/null +++ b/request_handler.go @@ -0,0 +1,38 @@ +package main + +import ( + "encoding/json" + "fmt" + "net/http" + "strings" + + "github.com/gabdlr/api-cuit-go/rate_limit" +) + +type CuitError struct { + Error string `json:"error"` +} + +const NO_SEARCH_ARG = "Sin argumento de búsqueda" + +func RequestHandler(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + + errorResponse := &CuitError{Error: "Fallo exitosamente"} + argument := r.URL.Path + + if len(argument) == 1 { + errorResponse.Error = NO_SEARCH_ARG + } else { + remoteAddr := (strings.Split(r.RemoteAddr, ":"))[0] + timeLeft := rate_limit.TimeLeft(remoteAddr) + + if timeLeft > 0 { + errorResponse.Error = fmt.Sprintf("Recurso no disponible, debe esperar %v segundos", timeLeft) + } + } + + jsonResponse, _ := json.Marshal(errorResponse) + w.Write(jsonResponse) +}