This repository has been archived by the owner on Dec 8, 2020. It is now read-only.
forked from shenghui0779/yiigo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
114 lines (84 loc) · 1.92 KB
/
request.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
105
106
107
108
109
110
111
112
113
114
package yiigo
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
)
// YiiClient HTTP request client
var YiiClient = &http.Client{
Timeout: 5 * time.Second,
}
// HTTPGet http get request
func HTTPGet(url string, headers map[string]string, timeout ...time.Duration) ([]byte, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
// custom headers
if len(headers) != 0 {
for k, v := range headers {
req.Header.Set(k, v)
}
}
// custom timeout
if len(timeout) > 0 {
YiiClient.Timeout = timeout[0]
}
resp, err := YiiClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("error http code: %d", resp.StatusCode)
}
if resp.Body == http.NoBody {
return nil, nil
}
b, err := ioutil.ReadAll(resp.Body)
return b, err
}
// HTTPPost http post request
func HTTPPost(url string, body []byte, headers map[string]string, timeout ...time.Duration) ([]byte, error) {
reader := bytes.NewReader(body)
req, err := http.NewRequest("POST", url, reader)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
// custom headers
if len(headers) != 0 {
for k, v := range headers {
req.Header.Set(k, v)
}
}
// custom timeout
if len(timeout) > 0 {
YiiClient.Timeout = timeout[0]
}
resp, err := YiiClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("error http code: %d", resp.StatusCode)
}
if resp.Body == http.NoBody {
return nil, nil
}
b, err := ioutil.ReadAll(resp.Body)
return b, err
}
// IsXhr checks if a request is xml-http-request (ajax).
func IsXhr(c *gin.Context) bool {
x := c.Request.Header.Get("X-Requested-With")
if strings.ToLower(x) == "xmlhttprequest" {
return true
}
return false
}