spider-core/biliapi/base.go

63 lines
1.2 KiB
Go
Raw Normal View History

2022-12-20 21:35:30 +08:00
package biliapi
import (
"io"
"net/http"
"net/url"
2022-12-20 21:35:30 +08:00
"time"
)
type Root struct {
Code int `json:"code"`
Message string `json:"message"`
TTL int `json:"ttl"`
Data interface{} `json:"data"`
}
type Jar struct {
cookies []*http.Cookie
}
func (jar *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) {
jar.cookies = cookies
}
func (jar *Jar) Cookies(u *url.URL) []*http.Cookie {
return jar.cookies
}
2022-12-20 21:35:30 +08:00
type BaseService struct {
Client *http.Client
Url string
Headers map[string]string
2022-12-20 21:35:30 +08:00
}
func (srv *BaseService) DoRequest() ([]byte, error) {
req, err := http.NewRequest("GET", srv.Url, nil)
2022-12-20 21:35:30 +08:00
if err != nil {
return nil, err
}
req.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.46")
if srv.Headers != nil {
for k, v := range srv.Headers {
req.Header.Add(k, v)
}
}
2022-12-20 21:35:30 +08:00
if srv.Client == nil {
srv.Client = &http.Client{
Timeout: 2 * time.Second,
2022-12-20 21:35:30 +08:00
}
}
resp, err := srv.Client.Do(req)
2022-12-20 21:35:30 +08:00
defer resp.Body.Close()
if err != nil {
return nil, err
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
}