一尘不染

使用http.Client和http.Transport设置请求标头

go

我有多个IP可以上网。我正在请求选择界面。在这种情况下,我应该如何设置标题?

tcpAddr := &net.TCPAddr{
    IP: addrs[3].(*net.IPNet).IP, // Choosing ip address number 3
}
d := net.Dialer{LocalAddr: tcpAddr}
conn, err2 := d.Dial("tcp", "www.whatismyip.com:80")
if err2 != nil {
    log.Fatal(err2)
}

defer conn.Close()

transport := &http.Transport{
    Proxy:               http.ProxyFromEnvironment,
    Dial:                (&net.Dialer{LocalAddr: tcpAddr}).Dial,
    TLSHandshakeTimeout: 10 * time.Second,
}

client := &http.Client{
    Transport: transport,
}

response, err := client.Get("https://www.whatismyip.com/")

通常,头是以这种方式设置的:

req.Header.Set("name", "value")

但是无法弄清楚如何将它们设置为我的代码。

我想它们必须放在http.Transport或中的某个位置http.Client。但是到底如何呢?

我的完整代码:

package main

import (
    "bytes"
    "fmt"
    "github.com/PuerkitoBio/goquery"
    "io/ioutil"
    "log"
    "net"
    "net/http"
    "os"
    "time"
)

func main() {
    ief, err := net.InterfaceByName("eth0")
    if err != nil {
        log.Fatal(err)
    }
    addrs, err := ief.Addrs()
    if err != nil {
        log.Fatal(err)
    }
    tcpAddr := &net.TCPAddr{
        IP: addrs[3].(*net.IPNet).IP, // Choosing ip address number 3
    }
    d := net.Dialer{LocalAddr: tcpAddr}
    conn, err2 := d.Dial("tcp", "www.whatismyip.com:80")
    if err2 != nil {
        log.Fatal(err2)
    }

    defer conn.Close()

    transport := &http.Transport{
        Proxy:               http.ProxyFromEnvironment,
        Dial:                (&net.Dialer{LocalAddr: tcpAddr}).Dial,
        TLSHandshakeTimeout: 10 * time.Second,
    }

    client := &http.Client{
        Transport: transport,
    }

    response, err := client.Get("https://www.whatismyip.com/")

    if err != nil {
        fmt.Printf("%s", err)
        os.Exit(1)
    } else {
        defer response.Body.Close()
        contents, err := ioutil.ReadAll(response.Body)
        if err != nil {
            fmt.Printf("%s", err)
            os.Exit(1)
        }
        var contentsStr = string(contents)
        fmt.Printf("%s\n", contentsStr)
        var doc = DocByHtmlString(contentsStr)

        doc.Find("div").Each(func(i int, s *goquery.Selection) {
            attr, exists := s.Attr("class")
            if exists {
                if attr == "ip" {
                    fmt.Println(s.Text())
                }
            }
        })
    }
}

func DocByHtmlString(html string) *goquery.Document {
    doc, err := goquery.NewDocumentFromReader(bytes.NewBufferString(html))
    if err != nil {
        panic(err)
    }
    return doc
}

阅读 1541

收藏
2020-07-02

共1个答案

一尘不染

创建一个请求:

 req, err := http.NewRequest("GET", "https://www.whatismyip.com/", nil)
 if err != nil {
  // handle error
 }

设置标题:

 req.Header.Set("name", "value")

使用client问题中配置的方式运行请求:

 resp, err := client.Do(req)
 if err != nil {
     // handle error
 }

按照问题所示处理响应。

2020-07-02