req
req copied to clipboard
可以使用SetSuccessResult获取原始响应内容吗?
var result string SetSuccessResult(&result)
这样无法正常获取 必须要 resp.body 的方式获取吗?
检测是json数据时, 使用jsonUnmarshal;
检测是xml时, 使用xmlUnmarshal;
其他情况使用jsonUnmarshal;
所以想要获取原始数据,可以使用:
var result json.RawMessage
SetSuccessResult(&result)
如果是xml内容, 你可以仿照json.RawMessage, 实现一个 xml.RawMessage
很好,非常感谢这位朋友的解答!但是并不能正常使用。
https://github.com/lib4u/grequest
var result string SetSuccessResult(&result)
这样无法正常获取 必须要 resp.body 的方式获取吗?
package test
import (
"errors"
"fmt"
"testing"
"github.com/imroc/req/v3"
)
func RawMessageUnmarshal(data []byte, v any) (err error) {
if ptr, ok := v.(*[]byte); ok {
*ptr = data
return nil
}
if unmarshal, ok := v.(interface{ UnmarshalJSON([]byte) error }); ok {
return unmarshal.UnmarshalJSON(data)
}
if unmarshal, ok := v.(interface{ UnmarshalText([]byte) error }); ok {
return unmarshal.UnmarshalText(data)
}
if unmarshal, ok := v.(interface{ UnmarshalBinary([]byte) error }); ok {
return unmarshal.UnmarshalBinary(data)
}
if unmarshal, ok := v.(interface{ Unmarshal([]byte) error }); ok {
return unmarshal.Unmarshal(data)
}
return errors.New("unmarshal type not supported")
}
func TestReq(t *testing.T) {
var result []byte
// var result json.RawMessage
_, err := req.
SetJsonUnmarshal(RawMessageUnmarshal).
R().
SetSuccessResult(&result).
Get("http://www.baidu.com/")
if err != nil {
panic(err)
}
fmt.Println(string(result))
}
@nicoxb 这确实可以使用,但是代码量较多,我还是老老实实的使用旧的方案吧,非常感谢。