golang,如何将http(s)代理转移到socks5代理

7cwmlq89  于 2023-10-14  发布在  Go
关注(0)|答案(1)|浏览(130)

proxy.SOCKS5支持keepalive吗?为什么我的长链接每25-26秒就断开一次?我想把http(s)代理请求转换成socks 5代理,然后再回去,你有办法吗?Golang http(s)如何转换为socks 5?

2g32fytz

2g32fytz1#

我想你可以使用**https://pkg.go.dev/golang.org/x/net/proxy**提供的Dialer接口
你可以尝试在你的代码中实现一个自定义的keep-alive机制!

package main

import (
    "fmt"
    "io"
    "net/http"
    "net/url"
    "time"

    "golang.org/x/net/proxy"
)

func main() {
    //create a SOCKS5 proxy dialer
    proxyURL, err := url.Parse("socks5://127.0.0.1:1080")
    if err != nil {
        fmt.Println("Failed to parse proxy URL:", err)
        return
    }
    dialer, err := proxy.FromURL(proxyURL, proxy.Direct)
    if err != nil {
        fmt.Println("Failed to create proxy dialer:", err)
        return
    }

    //make an HTTP client with the SOCKS5 proxy dialer
    httpClient := &http.Client{
        Transport: &http.Transport{
            Dial: dialer.Dial,
        },
    }

    //make a keep-alive goroutine
    go func() {
        for {
            //send a small HTTP GET request to keep the connection alive
            resp, err := httpClient.Get("http://example.com")
            if err != nil {
                fmt.Println("Failed to make request:", err)
                return
            }
            resp.Body.Close()

            //sleep for an interval (e.g., 20 seconds) before sending the next keep-alive request
            time.Sleep(20 * time.Second)
        }
    }()

    //make an HTTP request through the SOCKS5 proxy
    resp, err := httpClient.Get("http://example.com")
    if err != nil {
        fmt.Println("Failed to make request:", err)
        return
    }
    defer resp.Body.Close()

    //read and print the response body
    body, err := io.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("Failed to read response body:", err)
        return
    }
    fmt.Println(string(body))
}

相关问题