Skip to content

Commit 032983b

Browse files
committed
fix: parse json without errors
1 parent 85803f3 commit 032983b

File tree

4 files changed

+22
-61
lines changed

4 files changed

+22
-61
lines changed

gttp/bytes.go

-43
This file was deleted.

gttp/http.go

+4-2
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import (
77
"io"
88
"net/http"
99
"time"
10+
11+
"github.com/ochom/gutils/helpers"
1012
)
1113

1214
// Response is the response of the request.
@@ -52,7 +54,7 @@ func getTimeout(timeout ...time.Duration) time.Duration {
5254

5355
// Post sends a POST request to the specified URL.
5456
func Post(url string, headers M, body any, timeout ...time.Duration) (res *Response, err error) {
55-
req, err := http.NewRequest("POST", url, bytes.NewBuffer(ToBytes(body)))
57+
req, err := http.NewRequest("POST", url, bytes.NewBuffer(helpers.ToJSON(body)))
5658
if err != nil {
5759
return
5860
}
@@ -110,7 +112,7 @@ func Get(url string, headers M, timeout ...time.Duration) (res *Response, err er
110112

111113
// Custom sends a custom request to the specified URL.
112114
func Custom(url, method string, headers M, body any, timeout ...time.Duration) (res *Response, err error) {
113-
req, err := http.NewRequest(method, url, bytes.NewBuffer(ToBytes(body)))
115+
req, err := http.NewRequest(method, url, bytes.NewBuffer(helpers.ToJSON(body)))
114116
if err != nil {
115117
return
116118
}

helpers/csv.go

-12
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,6 @@ import (
44
"encoding/csv"
55
"io"
66
"os"
7-
"time"
8-
9-
"github.com/ochom/gutils/gttp"
107
)
118

129
// ParseCSV reads csv from io.Reader and returns a chan of slice of strings
@@ -44,12 +41,3 @@ func ReadFile(path string) ([]byte, error) {
4441

4542
return b, nil
4643
}
47-
48-
func DownloadFile(url string) ([]byte, error) {
49-
resp, err := gttp.Get(url, nil, 5*time.Minute)
50-
if err != nil {
51-
return nil, err
52-
}
53-
54-
return resp.Body, nil
55-
}

helpers/json.go

+18-4
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,28 @@ import (
77
)
88

99
// ToJSON converts a struct to JSON
10-
func ToJSON(v any) []byte {
11-
b, err := json.Marshal(v)
10+
func ToJSON(payload any) []byte {
11+
if payload == nil {
12+
return nil
13+
}
14+
15+
// Check if the payload is already of type []byte.
16+
if bytesPayload, ok := payload.([]byte); ok {
17+
return bytesPayload
18+
}
19+
20+
// Check if the payload is already of type string.
21+
if stringPayload, ok := payload.(string); ok {
22+
return []byte(stringPayload)
23+
}
24+
25+
// Marshal the payload to JSON.
26+
bytesPayload, err := json.Marshal(&payload)
1227
if err != nil {
13-
logs.Error("Failed to marshal JSON: %s", err.Error())
1428
return nil
1529
}
1630

17-
return b
31+
return bytesPayload
1832
}
1933

2034
// FromJSON converts json byte to struct

0 commit comments

Comments
 (0)