-
Notifications
You must be signed in to change notification settings - Fork 0
/
idjango.go
98 lines (89 loc) · 2.46 KB
/
idjango.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
package vcago
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"runtime"
)
//Mongo represents the initial struct for an Mongo connection.
type IDjangoHandler struct {
URL string
Key string
Export bool
}
//LoadEnv loads the Host and Port From .env file.
//Host can be set via NATS_HOST
//Port can be set via NATS_PORT
func NewIDjangoHandler() *IDjangoHandler {
return &IDjangoHandler{
URL: Settings.String("IDJANGO_URL", "w", "https://idjangostage.vivaconagua.org"),
Key: Settings.String("IDJANGO_KEY", "w", ""),
Export: Settings.Bool("IDJANGO_EXPORT", "w", false),
}
}
func (i *IDjangoHandler) Post(data interface{}, path string) (err error) {
if i.Export {
var jsonData []byte
if jsonData, err = json.Marshal(data); err != nil {
return
}
request := new(http.Request)
request, err = http.NewRequest("POST", i.URL+path, bytes.NewBuffer(jsonData))
request.Header.Set("Content-Type", "application/json; charset=UTF-8")
request.Header.Set("Authorization", "Api-Key "+i.Key)
client := &http.Client{}
response := new(http.Response)
response, err = client.Do(request)
if err != nil {
return NewIDjangoError(err, 500, nil)
}
defer response.Body.Close()
if response.StatusCode != 201 {
var bodyBytes []byte
if bodyBytes, err = ioutil.ReadAll(response.Body); err != nil {
return NewIDjangoError(err, response.StatusCode, nil)
}
body := new(interface{})
if err = json.Unmarshal(bodyBytes, body); err != nil {
return NewIDjangoError(err, 500, string(bodyBytes))
}
return NewIDjangoError(nil, response.StatusCode, body)
}
}
return
}
func NewIDjangoError(err error, code int, body interface{}) *IDjangoError {
var message = ""
if err != nil {
message = err.Error()
}
pc := make([]uintptr, 10)
runtime.Callers(3, pc)
f := runtime.FuncForPC(pc[0])
_, line := f.FileLine(pc[0])
file := runtime.FuncForPC(pc[0]).Name()
return &IDjangoError{
Err: err,
Message: message,
Code: code,
Body: body,
Line: line,
File: file,
}
}
type IDjangoError struct {
Err error `json:"error" bson:"error"`
Message string `json:"message" bson:"message"`
Code int `json:"code" bson:"code"`
Body interface{} `json:"body" bson:"body"`
Line int `json:"line" bson:"line"`
File string `json:"file" bson:"file"`
}
func (i *IDjangoError) Error() string {
return i.Message
}
func (i *IDjangoError) Log() string {
res, _ := json.Marshal(i)
return string(res)
}