internal/http_client.go
46 lines · 1054 bytes
1package internal
2
3import (
4 "fmt"
5 "net/http"
6 "net/http/cookiejar"
7 "net/url"
8 "strings"
9 "time"
10)
11
12var sharedHTTPClient *http.Client
13
14func SetCookiesForAnimepahe(u *url.URL, cookies []*http.Cookie) {
15 if sharedHTTPClient != nil && sharedHTTPClient.Jar != nil {
16 sharedHTTPClient.Jar.SetCookies(u, cookies)
17 }
18}
19
20func httpStatusOK(statusCode int) bool {
21 return statusCode >= http.StatusOK && statusCode < http.StatusMultipleChoices
22}
23
24func httpStatusError(context string, statusCode int, body []byte) error {
25 snippet := strings.TrimSpace(string(body))
26 if len(snippet) > 300 {
27 snippet = snippet[:300] + "..."
28 }
29 if snippet != "" {
30 return fmt.Errorf("%s failed with status %d: %s", context, statusCode, snippet)
31 }
32 return fmt.Errorf("%s failed with status %d", context, statusCode)
33}
34
35func init() {
36 jar, _ := cookiejar.New(nil)
37 sharedHTTPClient = &http.Client{
38 Transport: &http.Transport{
39 MaxIdleConns: 10,
40 MaxIdleConnsPerHost: 5,
41 IdleConnTimeout: 30 * time.Second,
42 },
43 Timeout: 15 * time.Second,
44 Jar: jar,
45 }
46}