-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
101 lines (92 loc) · 2.28 KB
/
main.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
package telegraph
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"strconv"
"strings"
"unicode"
)
var baseURL string = "https://api.graph.org/"
type response struct {
Ok bool `json:"ok"`
Result AllValueTypes `json:"result,omitempty"`
Error string `json:"error,omitempty"`
}
func Get(route string, opts interface{}) (*AllValueTypes, error) {
vs := url.Values{}
v := reflect.ValueOf(opts)
t := v.Type()
for i := 0; i < v.NumField(); i++ {
val := v.Field(i).Interface()
key := t.Field(i).Name
if !isZeroOfType(val) {
var str string
switch vt := val.(type) {
case int64:
str = strconv.FormatInt(vt, 10)
case bool:
str = strconv.FormatBool(vt)
case []string:
str = fmt.Sprintf(`["%v"]`, strings.Join(vt, `","`))
case []Node:
str = NodeToQueryString(vt)
default:
str = vt.(string)
}
vs.Add(snaking(key), str)
}
}
u := baseURL + route + "?" + vs.Encode()
var jsonData response
r, e := http.Get(u)
bs, _ := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if e != nil {
return &AllValueTypes{}, e
}
json.Unmarshal(bs, &jsonData)
if !jsonData.Ok {
return &AllValueTypes{}, fmt.Errorf(jsonData.Error)
}
return &jsonData.Result, nil
}
func Post(route string, opts interface{}) (*AllValueTypes, error) {
u := baseURL + route
var jsonData response
bs, _ := json.Marshal(opts)
r, e := http.Post(u, "application/json", bytes.NewReader(bs))
bs, _ = ioutil.ReadAll(r.Body)
defer r.Body.Close()
if e != nil {
return &AllValueTypes{}, e
}
json.Unmarshal(bs, &jsonData)
if !jsonData.Ok {
return &AllValueTypes{}, fmt.Errorf(jsonData.Error)
}
return &jsonData.Result, nil
}
// ------------------- Helpers ------------------ //
func isZeroOfType(x interface{}) bool {
return reflect.DeepEqual(x, reflect.Zero(reflect.TypeOf(x)).Interface())
}
func Prettify(t interface{}) string {
b, _ := json.MarshalIndent(t, "", " ")
return string(b)
}
// This is specific for these cases and can't be used in general
func snaking(s string) string {
s = strings.ReplaceAll(s, "URL", "_url") // Exceptional
c := s[1:]
for _, char := range c {
if unicode.IsUpper(char) {
c = strings.Replace(c, string(char), "_"+strings.ToLower(string(char)), -1)
}
}
return strings.ToLower(string(s[0])) + c
}