aboutsummaryrefslogtreecommitdiff
path: root/internal/http/client.go
blob: 17eb0cce93fe0f00345cdce012264ae23354e322 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package http

import (
	ctxt "context"
	"crypto/tls"
	"fmt"
	"net/http"
	"time"
)

// share HTTP clients
var (
	stdClient    *http.Client
	unsafeClient *http.Client
)

// Error represents an HTTP error returned by a server.
type Error struct {
	StatusCode int
	Status     string
}

type Context struct {
	Timeout    int
	DisableTLS bool
}

func (err Error) Error() string {
	return fmt.Sprintf("http error: %s", err.Status)
}

func init() {
	// std
	stdClient = &http.Client{Transport: http.DefaultTransport}

	// unsafe
	tlsConfig := &tls.Config{InsecureSkipVerify: true}
	transport := http.DefaultTransport.(*http.Transport).Clone()
	transport.TLSClientConfig = tlsConfig
	unsafeClient = &http.Client{Transport: transport}
}

func (ctx Context) StdContext() (ctxt.Context, ctxt.CancelFunc) {
	return ctxt.WithTimeout(ctxt.Background(), time.Duration(ctx.Timeout)*time.Second)
}

func client(disableTLS bool) *http.Client {
	if disableTLS {
		return unsafeClient
	}
	return stdClient
}

var noop ctxt.CancelFunc = func() {}

func Get(url string, ctx Context) (resp *http.Response, cancel ctxt.CancelFunc, err error) {
	prematureExit := true
	stdCtx, ctxCancel := ctx.StdContext()

	cancel = func() {
		if resp != nil {
			_ = resp.Body.Close()
		}
		ctxCancel()
	}

	defer func() {
		if prematureExit {
			cancel()
		}
	}()

	req, err := http.NewRequestWithContext(stdCtx, "GET", url, nil)
	if err != nil {
		return nil, noop, err
	}
	req.Header.Set("User-Agent", "Feed2Imap-Go/1.0")

	resp, err = client(ctx.DisableTLS).Do(req)
	if err != nil {
		return nil, noop, err
	}

	if resp.StatusCode < 200 || resp.StatusCode >= 300 {
		return nil, noop, Error{
			StatusCode: resp.StatusCode,
			Status:     resp.Status,
		}
	}

	prematureExit = false
	return resp, cancel, nil
}