代码拉取完成,页面将自动刷新
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
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。