aboutsummaryrefslogtreecommitdiff
path: root/fasthttpproxy
diff options
context:
space:
mode:
authorGravatar Erik Dubbelboer <erik@dubbelboer.com> 2020-04-20 18:30:10 +0200
committerGravatar Erik Dubbelboer <erik@dubbelboer.com> 2020-04-20 18:32:19 +0200
commit54df169029f1c9f03afe9c830c9aa4ab0ad025d7 (patch)
treeb56f6bbc327dc4926c2594637ae6805893536645 /fasthttpproxy
parentUpgrade dependencies (diff)
downloadfasthttp-54df169029f1c9f03afe9c830c9aa4ab0ad025d7.tar.gz
fasthttp-54df169029f1c9f03afe9c830c9aa4ab0ad025d7.tar.bz2
fasthttp-54df169029f1c9f03afe9c830c9aa4ab0ad025d7.zip
Add fasthttpproxy.FasthttpHTTPDialerv1.12.0
Diffstat (limited to 'fasthttpproxy')
-rw-r--r--fasthttpproxy/http.go61
1 files changed, 61 insertions, 0 deletions
diff --git a/fasthttpproxy/http.go b/fasthttpproxy/http.go
new file mode 100644
index 0000000..2879408
--- /dev/null
+++ b/fasthttpproxy/http.go
@@ -0,0 +1,61 @@
+package fasthttpproxy
+
+import (
+ "bufio"
+ "encoding/base64"
+ "fmt"
+ "net"
+ "strings"
+
+ "github.com/valyala/fasthttp"
+)
+
+// FasthttpHTTPDialer returns a fasthttp.DialFunc that dials using
+// the provided HTTP proxy.
+//
+// Example usage:
+// c := &fasthttp.Client{
+// Dial: fasthttpproxy.FasthttpHTTPDialer("username:password@localhost:9050"),
+// }
+func FasthttpHTTPDialer(proxy string) fasthttp.DialFunc {
+ return func(addr string) (net.Conn, error) {
+ var auth string
+
+ if strings.Contains(proxy, "@") {
+ split := strings.Split(proxy, "@")
+ auth = base64.StdEncoding.EncodeToString([]byte(split[0]))
+ proxy = split[1]
+
+ }
+
+ conn, err := fasthttp.Dial(proxy)
+ if err != nil {
+ return nil, err
+ }
+
+ req := "CONNECT " + addr + " HTTP/1.1\r\n"
+ if auth != "" {
+ req += "Proxy-Authorization: Basic " + auth + "\r\n"
+ }
+ req += "\r\n"
+
+ if _, err := conn.Write([]byte(req)); err != nil {
+ return nil, err
+ }
+
+ res := fasthttp.AcquireResponse()
+ defer fasthttp.ReleaseResponse(res)
+
+ res.SkipBody = true
+
+ if err := res.Read(bufio.NewReader(conn)); err != nil {
+ conn.Close()
+ return nil, err
+ }
+ if res.Header.StatusCode() != 200 {
+ conn.Close()
+ return nil, fmt.Errorf("could not connect to proxy")
+ }
+ return conn, nil
+ }
+}