golang http 客户端使用 http/socks 代理

admin 2020-07-14 PM 1571℃ 0条

网上流传的用法大都引用了 golang.org/x/net/proxy(并且使用了已经 deprecateddialer),实际上现在可以直接用这种更简单的写法。

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "net/url"
)

const (
    HttpProxy  = "http://127.0.0.1:6152"
    SocksProxy = "socks5://127.0.0.1:6153"
)

func main() {
    proxy := func(_ *http.Request) (*url.URL, error) {
        return url.Parse(HttpProxy)
    }

    httpTransport := &http.Transport{
        Proxy: proxy,
    }

    httpClient := &http.Client{
        Transport: httpTransport,
    }

    req, err := http.NewRequest("GET", "https://api.ip.sb/ip", nil)
    if err != nil {
        // handle error     }

    resp, err := httpClient.Do(req)
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        // handle error     }

    fmt.Println(string(body))

    proxy = func(_ *http.Request) (*url.URL, error) {
        return url.Parse(SocksProxy)
    }

    httpTransport = &http.Transport{
        Proxy: proxy,
    }

    httpClient = &http.Client{
        Transport: httpTransport,
    }

    req, err = http.NewRequest("GET", "https://api.ip.sb/ip", nil)
    if err != nil {
        // handle error     }

    resp, err = httpClient.Do(req)
    defer resp.Body.Close()

    body, err = ioutil.ReadAll(resp.Body)
    if err != nil {
        // handle error     }

    fmt.Println(string(body))
}

可以验证:打印的响应中确实为代理 IP。

标签: none

非特殊说明,本博所有文章均为博主原创。

评论啦~