-
Notifications
You must be signed in to change notification settings - Fork 174
/
responseCastable.go
93 lines (75 loc) · 2.21 KB
/
responseCastable.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
package support
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/ArtisanCloud/PowerLibs/v3/object"
response2 "github.com/ArtisanCloud/PowerWeChat/v3/src/kernel/response"
"go/types"
"io/ioutil"
"net/http"
"reflect"
)
type ResponseCastable struct {
}
func (responseCastable *ResponseCastable) CastResponseToType(response *http.Response, castType string) (interface{}, error) {
if castType == response2.TYPE_RAW {
return response, nil
}
switch castType {
case response2.TYPE_ARRAY:
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
data := []interface{}{}
err = json.Unmarshal(body, data)
return data, err
case response2.TYPE_MAP:
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
data := &object.HashMap{}
err = json.Unmarshal(body, data)
return data, err
case response2.TYPE_RAW:
return response, nil
default:
return nil, errors.New("Config key \"response_type\" classname must be an instanceof %s'")
}
}
func (responseCastable *ResponseCastable) DetectAndCastResponseToType(response interface{}, toType string) (interface{}, error) {
var returnResponse http.Response = http.Response{
StatusCode: 200,
Header: nil,
}
switch response.(type) {
case http.Response:
returnResponse = response.(http.Response)
break
case *http.Response:
returnResponse = *response.(*http.Response)
break
case types.Array:
postBodyBuf, _ := json.Marshal(response.(types.Array))
returnResponse.Body = ioutil.NopCloser(bytes.NewBuffer(postBodyBuf))
break
case object.HashMap:
postBodyBuf, _ := json.Marshal(response.(object.HashMap))
returnResponse.Body = ioutil.NopCloser(bytes.NewBuffer(postBodyBuf))
break
case *object.HashMap:
postBodyBuf, _ := json.Marshal(response.(*object.HashMap))
returnResponse.Body = ioutil.NopCloser(bytes.NewBuffer(postBodyBuf))
break
case string:
postBodyBuf, _ := json.Marshal(response.(string))
returnResponse.Body = ioutil.NopCloser(bytes.NewBuffer(postBodyBuf))
break
default:
return nil, errors.New(fmt.Sprintf("unsupported response type '%s'", reflect.TypeOf(response).Kind().String()))
}
return responseCastable.CastResponseToType(&returnResponse, toType)
}