-
Notifications
You must be signed in to change notification settings - Fork 0
/
SendJsonHeader.go
94 lines (75 loc) · 2.11 KB
/
SendJsonHeader.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
package models
import (
"bytes"
"encoding/json"
"github.com/astaxie/beego"
"github.com/astaxie/beego/context"
"net/http"
)
var global *context.Context
func SendJson(urlp string, trequest string, target interface{}, datajson interface{}) error {
b := new(bytes.Buffer)
if datajson != nil {
json.NewEncoder(b).Encode(datajson)
}
//proxyUrl, err := url.Parse("http://10.20.4.15:3128")
//http.DefaultTransport = &http.Transport{Proxy: http.ProxyURL(proxyUrl)}
client := &http.Client{}
req, err := http.NewRequest(trequest, urlp, b)
req.Header.Set("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")
//Se intenta acceder a cabecera, si no existe, se realiza peticion normal.
defer func() {
//Catch
if r := recover(); r != nil {
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
beego.Error("Error reading response. ", err)
}
defer resp.Body.Close()
json.NewDecoder(resp.Body).Decode(target)
}
}()
//try
header := GetHeader().Request.Header
req.Header.Set("Authorization", header["Authorization"][0])
resp, err := client.Do(req)
if err != nil {
beego.Error("Error reading response. ", err)
}
defer resp.Body.Close()
return json.NewDecoder(resp.Body).Decode(target)
}
func GetHeader() (ctx *context.Context) {
return global
}
func GetJson(urlp string, target interface{}) error {
req, err := http.NewRequest("GET", urlp, nil)
if err != nil {
beego.Error("Error reading request. ", err)
}
//Se intenta acceder a cabecera, si no existe, se realiza peticion normal.
defer func() {
//Catch
if r := recover(); r != nil {
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
beego.Error("Error reading response. ", err)
}
defer resp.Body.Close()
json.NewDecoder(resp.Body).Decode(target)
}
}()
//try
header := GetHeader().Request.Header
req.Header.Set("Authorization", header["Authorization"][0])
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
beego.Error("Error reading response. ", err)
}
defer resp.Body.Close()
return json.NewDecoder(resp.Body).Decode(target)
}