doushijia5684 2015-09-12 14:59
浏览 378
已采纳

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

I have more than one ip to go to the internet. I am making request choosing interface. In this case how should I set headers?

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/")

Usually headers are set in this way:

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

But cannot figure out how to set them to my code.

I guess they must be set somewhere in http.Transport or http.Client. But how exactly?

My full code:

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
", 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
}
  • 写回答

1条回答 默认 最新

  • dourukeng5302 2015-09-12 15:12
    关注

    Create a request:

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

    Set the headers:

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

    Run the request using client as configured in the question:

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

    Handle the response as shown in the question.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?