首先,创建带有Cancel Context的http请求
var cx context.Context cx, req.cancel = context.WithCancel(context.Background()) if req.httpreq, err = http.NewRequest(req.method, req.url, reqbody); err != nil { return } req.httpreq = req.httpreq.WithContext(cx) req.httpreq.Header = req.Headers req.httpreq.ContentLength = reqbodyLength
然后,需要停止请求的时候调用req.cancel()方法
if req.cancel != nil { req.cancel() fmt.Println("running cancel...") } return nil
这样才能够客户端强行主动取消正在进行的http连接。就是这么简单