1 Star 0 Fork 0

cruller/gummy

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
response.go 2.67 KB
一键复制 编辑 原始数据 按行查看 历史
跳舞的地瓜 提交于 2024-01-09 15:35 . 解决重试功能不起作用
package gummy
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
"gitee.com/cruller/gummy/content"
"github.com/PuerkitoBio/goquery"
)
type Response struct {
res *http.Response
err error
ctx *Context
expCts []string
}
func pkgResponse(ctx *Context, res *http.Response, err error) *Response {
newRes := new(Response)
newRes.res = res
newRes.ctx = ctx
newRes.err = err
return newRes
}
func (res *Response) Expect(contentTypes ...string) *Response {
if cts, dup := res.res.Header["Content-Type"]; dup {
cts = strings.Split(cts[0], ";")
for _, act := range cts {
act = strings.ToLower(act)
for _, bct := range contentTypes {
bct = strings.ToLower(bct)
if act == bct {
res.expCts = nil
return res
}
}
}
}
res.err = fmt.Errorf("there is no expected outcome")
res.expCts = contentTypes
return res
}
func (res *Response) Retry(ns ...int) *Response {
if len(ns) == 0 || ns[0] < 0 {
for {
if nil == res.err {
return res
}
res.ctx.sleep()
res = res.retry()
}
}
n := ns[0]
for i := 0; i < n; i++ {
if nil == res.err {
return res
}
res.ctx.sleep()
res = res.retry()
}
return res
}
func (res *Response) retry() *Response {
res = res.ctx.retry()
if nil != res.expCts {
res = res.Expect(res.expCts...)
}
fmt.Println("重试", res.ctx.req.URL)
return res
}
func (res *Response) Sleep(d time.Duration) *Response {
res.ctx.sleepDuration = d
return res
}
func (res *Response) String() string {
if res.ctx.req == nil {
return ""
}
req := res.ctx.req
return fmt.Sprintf("%s %s", req.Method, req.URL)
}
func (res *Response) Body() (body io.ReadCloser, err error) {
if encodes, dup := res.res.Header["Content-Encoding"]; dup && len(encodes) > 0 {
return content.DecodeBody(encodes[0], res.res.Body)
}
return res.res.Body, nil
}
func (res *Response) GetBytes() (code int, data []byte, err error) {
if nil != res.err {
return 0, nil, res.err
}
code = res.res.StatusCode
body, err := res.Body()
if nil != err {
return 0, nil, err
}
defer body.Close()
data, err = io.ReadAll(body)
return
}
func (res *Response) GetString() (code int, data string, err error) {
var buf []byte
code, buf, err = res.GetBytes()
return code, string(buf), err
}
func (res *Response) GetJSON(v any) (code int, err error) {
var data []byte
code, data, err = res.GetBytes()
if nil != err {
return code, err
}
return code, json.Unmarshal(data, v)
}
func (res *Response) GetDocument() (code int, dom *goquery.Document, err error) {
code = res.res.StatusCode
body, err := res.Body()
if nil != err {
return 0, nil, err
}
defer body.Close()
dom, err = goquery.NewDocumentFromReader(body)
return code, dom, err
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/cruller/gummy.git
git@gitee.com:cruller/gummy.git
cruller
gummy
gummy
main

搜索帮助