1 | package fasthttpproxy
|
---|
2 |
|
---|
3 | import (
|
---|
4 | "bufio"
|
---|
5 | "encoding/base64"
|
---|
6 | "fmt"
|
---|
7 | "net"
|
---|
8 | "strings"
|
---|
9 | "time"
|
---|
10 |
|
---|
11 | "github.com/valyala/fasthttp"
|
---|
12 | )
|
---|
13 |
|
---|
14 | // FasthttpHTTPDialer returns a fasthttp.DialFunc that dials using
|
---|
15 | // the provided HTTP proxy.
|
---|
16 | //
|
---|
17 | // Example usage:
|
---|
18 | // c := &fasthttp.Client{
|
---|
19 | // Dial: fasthttpproxy.FasthttpHTTPDialer("username:password@localhost:9050"),
|
---|
20 | // }
|
---|
21 | func FasthttpHTTPDialer(proxy string) fasthttp.DialFunc {
|
---|
22 | return FasthttpHTTPDialerTimeout(proxy, 0)
|
---|
23 | }
|
---|
24 |
|
---|
25 | // FasthttpHTTPDialerTimeout returns a fasthttp.DialFunc that dials using
|
---|
26 | // the provided HTTP proxy using the given timeout.
|
---|
27 | //
|
---|
28 | // Example usage:
|
---|
29 | // c := &fasthttp.Client{
|
---|
30 | // Dial: fasthttpproxy.FasthttpHTTPDialerTimeout("username:password@localhost:9050", time.Second * 2),
|
---|
31 | // }
|
---|
32 | func FasthttpHTTPDialerTimeout(proxy string, timeout time.Duration) fasthttp.DialFunc {
|
---|
33 | var auth string
|
---|
34 | if strings.Contains(proxy, "@") {
|
---|
35 | split := strings.Split(proxy, "@")
|
---|
36 | auth = base64.StdEncoding.EncodeToString([]byte(split[0]))
|
---|
37 | proxy = split[1]
|
---|
38 | }
|
---|
39 |
|
---|
40 | return func(addr string) (net.Conn, error) {
|
---|
41 | var conn net.Conn
|
---|
42 | var err error
|
---|
43 | if timeout == 0 {
|
---|
44 | conn, err = fasthttp.Dial(proxy)
|
---|
45 | } else {
|
---|
46 | conn, err = fasthttp.DialTimeout(proxy, timeout)
|
---|
47 | }
|
---|
48 | if err != nil {
|
---|
49 | return nil, err
|
---|
50 | }
|
---|
51 |
|
---|
52 | req := fmt.Sprintf("CONNECT %s HTTP/1.1\r\nHost: %s\r\n", addr, addr)
|
---|
53 | if auth != "" {
|
---|
54 | req += "Proxy-Authorization: Basic " + auth + "\r\n"
|
---|
55 | }
|
---|
56 | req += "\r\n"
|
---|
57 |
|
---|
58 | if _, err := conn.Write([]byte(req)); err != nil {
|
---|
59 | return nil, err
|
---|
60 | }
|
---|
61 |
|
---|
62 | res := fasthttp.AcquireResponse()
|
---|
63 | defer fasthttp.ReleaseResponse(res)
|
---|
64 |
|
---|
65 | res.SkipBody = true
|
---|
66 |
|
---|
67 | if err := res.Read(bufio.NewReader(conn)); err != nil {
|
---|
68 | conn.Close()
|
---|
69 | return nil, err
|
---|
70 | }
|
---|
71 | if res.Header.StatusCode() != 200 {
|
---|
72 | conn.Close()
|
---|
73 | return nil, fmt.Errorf("could not connect to proxy: %s status code: %d", proxy, res.Header.StatusCode())
|
---|
74 | }
|
---|
75 | return conn, nil
|
---|
76 | }
|
---|
77 | }
|
---|