使用http.Client和http.Transport为请求设置头部。

huangapple go评论92阅读模式
英文:

set headers for request using http.Client and http.Transport

问题

我有多个IP地址可以连接到互联网。我正在选择接口进行请求。在这种情况下,我应该如何设置头部?

通常情况下,可以按照以下方式设置头部:

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

但是我无法确定如何将它们设置到我的代码中。

我猜它们必须在http.Transporthttp.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, // 选择第3个IP地址
	}
	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
}

希望对你有帮助!

英文:

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
}

答案1

得分: 9

创建一个请求:

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

设置请求头:

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

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

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

按照问题中的示例处理响应。

英文:

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.

huangapple
  • 本文由 发表于 2015年9月12日 22:59:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/32540219.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定