使用http.Client和http.Transport为请求设置标头 [英] set headers for request using http.Client and http.Transport

查看:329
本文介绍了使用http.Client和http.Transport为请求设置标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有超过一个ip去上网。我正在请求选择界面。在这种情况下,我应该如何设置标题?

  tcpAddr:=& net.TCPAddr {
IP:addrs [ 3]。(* net.IPNet).IP,//选择ip地址号码3
}
d:= net.Dialer {LocalAddr:tcpAddr}
conn,err2:= d.Dial (tcp,www.whatismyip.com:80)
if err2!= nil {
log.Fatal(err2)
}

推迟conn .Close()

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

客户端:=& http.Client {
运输:运输,
}

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

通常,标头设置在此方式

  req.Header.Set(name,value)

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



我猜他们必须设置在 http.Transport http.Client 。但究竟如何?

我的完整代码:

  package main 

导入(
字节
fmt
github.com/PuerkitoBio/goquery
io / ioutil
日志

净/ http
os
时间


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,//选择ip地址号码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/)

如果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)。每个(func(i int,s * goquery.Selection){
attr,存在:= s.Attr(class)
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
}


解决方案

创建请求:

  req,err:= http.NewRequest(GET,https://www.whatismyip.com/,无)
if err!= nil {
//处理错误
}

设置标题:

  req.Header.Set(name,value)

使用客户端按问题中的配置运行请求:

  resp,err:= client.Do(req)
if err!= nil {
//处理错误
}

处理问题中显示的回复。


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\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
}

解决方案

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.

这篇关于使用http.Client和http.Transport为请求设置标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆