/
handles_http.go
64 lines (53 loc) · 1.23 KB
/
handles_http.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
// Author: yangzq80@gmail.com
// Date: 2021-04-06
//
package server
import (
"bytes"
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"io/ioutil"
"net/http"
"strings"
)
type DoClient struct {
Url string
Method string
Headers string
//Data *json.RawMessage `json:"data,ommitempty"`
//Data map[string]interface{}
Data interface{}
}
func (s *Server) doHttp(c *gin.Context) {
var client DoClient
if err := c.ShouldBind(&client); err == nil {
c.JSON(http.StatusOK, getUrl(client))
} else {
c.JSON(http.StatusBadRequest, err.Error())
}
}
func getUrl(do DoClient) json.RawMessage {
var jsonStr = []byte("")
if r, err := json.Marshal(do.Data); err == nil {
jsonStr = r
}
if do.Method == "" {
do.Method = "GET"
} else {
do.Method = strings.ToUpper(do.Method)
}
req, err := http.NewRequest(do.Method, do.Url, bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
return []byte("http.get i/o timeout")
}
defer resp.Body.Close()
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))
return body
}