From ce61e724c9ae08d5bd1450915af645fe8d98a036 Mon Sep 17 00:00:00 2001 From: qydysky Date: Sun, 11 Apr 2021 17:13:07 +0800 Subject: [PATCH] reqf --- Reqf.go => reqf/Reqf.go | 17 +++++++++++++---- reqf/Reqf_test.go | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 4 deletions(-) rename Reqf.go => reqf/Reqf.go (95%) create mode 100644 reqf/Reqf_test.go diff --git a/Reqf.go b/reqf/Reqf.go similarity index 95% rename from Reqf.go rename to reqf/Reqf.go index f8dc9f7..b299c26 100644 --- a/Reqf.go +++ b/reqf/Reqf.go @@ -95,10 +95,6 @@ func (this *req) Reqf_1(val Rval) (error) { if Header == nil {Header = make(map[string]string)} - if Timeout != -1 { - client.Timeout = time.Duration(Timeout)*time.Second - } - if Proxy!="" { proxy := func(_ *http.Request) (*url.URL, error) { return url.Parse(Proxy) @@ -119,6 +115,9 @@ func (this *req) Reqf_1(val Rval) (error) { } cx, cancel := context.WithCancel(context.Background()) + if Timeout != -1 { + cx, _ = context.WithTimeout(cx,time.Duration(Timeout)*time.Second) + } req,_ := http.NewRequest(Method, Url, body) req = req.WithContext(cx) @@ -200,6 +199,8 @@ func (this *req) Reqf_1(val Rval) (error) { return nil } +func (t *req) Cancel(){t.Close()} + func (t *req) Close(){ if !t.cancelOpen {return} select { @@ -238,4 +239,12 @@ func Cookies_List_2_Map(Cookies []*http.Cookie) (o map[string]string) { o[v.Name] = v.Value } return +} + +func IsTimeout(e error) bool { + return errors.Is(e, context.DeadlineExceeded) +} + +func IsCancel(e error) bool { + return errors.Is(e, context.Canceled) } \ No newline at end of file diff --git a/reqf/Reqf_test.go b/reqf/Reqf_test.go new file mode 100644 index 0000000..29d65bd --- /dev/null +++ b/reqf/Reqf_test.go @@ -0,0 +1,39 @@ +package part + +import ( + "testing" + "time" +) + +func Test_Timeout(t *testing.T) { + r := Req() + if e := r.Reqf(Rval{ + Url:`https://cdimage.debian.org/debian-cd/current/amd64/iso-cd/debian-10.9.0-amd64-netinst.iso`, + Timeout:1, + });e != nil { + if !IsTimeout(e) { + t.Error(`type error`,e) + } + return + } + t.Error(`no error`) +} + +func Test_Cancel(t *testing.T) { + r := Req() + + go func(){ + time.Sleep(time.Second) + r.Cancel() + }() + + if e := r.Reqf(Rval{ + Url:`https://cdimage.debian.org/debian-cd/current/amd64/iso-cd/debian-10.9.0-amd64-netinst.iso`, + });e != nil { + if !IsCancel(e) { + t.Error(`type error`,e) + } + return + } + t.Error(`no error`) +} \ No newline at end of file -- 2.39.2