Skip to content

增添 V2 版本

Latest

Choose a tag to compare

@Fromsko Fromsko released this 15 Oct 13:14
· 3 commits to main since this release

新增 v2 版本

调用

func main(){
	// 适配器调用
	reqOne := v2.NewRequest(
		v2.WithURL("https://www.baidu.com"),
		v2.WithProxy("http://127.0.0.1:7890"),
		v2.WithMethod(http.MethodGet),
	)

	// 链式调用
	reqTwo := v2.NewRequest().
		WithURL("https://www.baidu.com").
		WithProxy("http://127.0.0.1:7890").
		WithMethod(http.MethodGet)

	reqOne.Send(func(resp v2.IResponse, err error) {
		// 接口实现
		resp.Bytes()        // []byte
		resp.Json()         // *gjson.Result
		resp.RaiseCode(200) // error
		resp.StatusCode()   // resp.code => 200
		resp.WriteFile("demo.txt", "0777", "")
		resp.WriteJson("demo.json", "0777", "")

		// 原始响应数据
		body := resp.(*v2.Response).Body
		contentTypeLen := resp.(*v2.Response).Resp.ContentLength
		fmt.Printf("body: %v\n", body)
		fmt.Printf("contentTypeLen: %v\n", contentTypeLen)
	})
}

新增两个接口

// IRequest 接口,定义请求的行为
type IRequest interface {
	WithURL(url string) IRequest
	WithMethod(method string) IRequest
	WithData(data io.Reader) IRequest
	WithForm(form url.Values) IRequest
	WithProxy(url string) IRequest
	WithCookies(cookies []*http.Cookie) IRequest
	WithHeaders(headers map[string]string) IRequest
	Send(callBack func(resp IResponse, err error))
}

// IResponse 接口,定义响应的行为
type IResponse interface {
	StatusCode() int
	Json() *gjson.Result
	Text() string
	Bytes() []byte
	RaiseCode(code int) error
	WriteFile(fileName, perm, dir string) error
	WriteJson(fileName, perm, dir string) error
}