fixed error handling and other types into request methods

This commit is contained in:
Valmo Trindade
2024-07-23 19:26:46 -03:00
parent 8603dd6d93
commit e7dc9c09c2

View File

@@ -21,46 +21,48 @@ func getRequest(route string) (string, error) {
req, err := http.Get(endpoint) req, err := http.Get(endpoint)
if err != nil { if err != nil {
return "", fmt.Errorf("Error creating request: %w", err) return "", fmt.Errorf("getting Error creating request: %w", err)
} }
defer req.Body.Close() defer req.Body.Close()
if req.StatusCode != http.StatusOK { if req.StatusCode != http.StatusOK {
return "", fmt.Errorf("Error sending request: %w", req.Status) return "", fmt.Errorf("getting Error sending request " + req.Status)
} }
body, err := io.ReadAll(req.Body) body, err := io.ReadAll(req.Body)
if err != nil { if err != nil {
return "", fmt.Errorf("Error reading response body: %w", err) return "", fmt.Errorf("getting Error reading response body %w", err)
} }
return string(body), nil return string(body), nil
} }
func postRequest(route string, body string) { func postRequest(route string, body any) (string, error) {
endpoint := FreeTAKServerURL + route jsonData, err := json.Marshal(body)
payload := Payload{
Content: body,
}
jsonData, err := json.Marshal(payload)
if err != nil { if err != nil {
fmt.Println("Error marshalling payload:", err) fmt.Println("Error marshalling payload:", err)
return return "", err
} }
req, err := http.Post(endpoint, "application/json", bytes.NewReader(jsonData)) req, err := http.Post(route, "application/json", bytes.NewReader(jsonData))
if err != nil { if err != nil {
fmt.Println("Error creating request:", err) fmt.Println("Error creating request:", err)
return return "", err
} }
defer req.Body.Close() defer req.Body.Close()
if req.StatusCode != http.StatusOK { if req.StatusCode != http.StatusOK {
fmt.Println("Error sending request:", req.Status) fmt.Println("Error sending request:", req.Status)
return return "", nil
} }
parsedBody, err := io.ReadAll(req.Body)
if err != nil {
return "", fmt.Errorf("getting Error reading response body: %w", err)
}
return string(parsedBody), nil
} }