This repository has been archived by the owner on Jul 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
104 lines (87 loc) · 2.49 KB
/
util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package gobizApi
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
var IsDebug bool = false
func marshalJSON(data interface{}) ([]byte, error) {
jsonValue, err := json.Marshal(data)
if err != nil {
return nil, fmt.Errorf("Error marshaling JSON data: %v", err)
}
return jsonValue, nil
}
func unmarshalJSON(data []byte, target interface{}) error {
err := json.Unmarshal(data, target)
if err != nil {
return fmt.Errorf("Error unmarshaling JSON data: %v", err)
}
return nil
}
func printError(err error) {
if IsDebug {
if err != nil {
fmt.Println("Error : ", err)
}
}
}
func printResponse(ok string) {
if IsDebug {
if ok != "" {
fmt.Println("Response : ", ok)
}
}
}
func sendRequest(req *http.Request, authorization string) ([]byte, error) {
setRequestHeaders(req, authorization, true)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("Error making request: %v", err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("Error reading response: %v", err)
}
if resp.StatusCode != http.StatusOK {
printResponse("Debug Response : " + string(body))
return body, fmt.Errorf("Request failed with status: %d", resp.StatusCode)
}
return body, nil
}
func sendRequestGuest(req *http.Request) ([]byte, error) {
setRequestHeaders(req, "", false)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("Error making request: %v", err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("Error reading response: %v", err)
}
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
printResponse("Debug Response: " + string(body))
return body, fmt.Errorf("Request failed with status: %d", resp.StatusCode)
}
return body, nil
}
func setRequestHeaders(req *http.Request, authorization string, isAuthenticated bool) {
req.Header.Set("X-User-Type", "merchant")
req.Header.Set("X-Client-Id", "go-biz-mobile")
req.Header.Set("X-Client-Secret", "sPC0qVk7gi76JUoGVfOfcgd7FfuaBv")
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "okhttp/3.12.10")
if isAuthenticated {
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", authorization))
} else {
req.Header.Set("X-Platform", "Android")
req.Header.Set("X-Appversion", "4.4.0")
req.Header.Set("X-Appid", "com.gojek.resto")
}
}