
在公司内部,经常会有域名是需要绑定host才能访问的,如果是通过浏览器访问,我们会修改本机的hosts文件;然而,如果是要通过程序访问这样的域名,我们是否依然必须绑定host呢?答案当然是否定的,而且,依赖本地绑定的host,程序到其他机器部署,也必须在那台机器绑定host,如果机器很多呢?
本文示例:
IP:192.168.1.102,也就是说需要访问这台机器上的资源
域名:www.studygolang.com,nginx 配置的虚拟主机
url path:/testhost.txt,内容是:Welcome to studygolang.com
需求:需要请求服务器上的 testhost.txt 资源
1、Linux Shell的解决方案
Linux下的curl程序可以绑定host,因此,在 shell 中可以很简单的实现,如: curl -H “Host:www.studygolang.com” http://192.168.1.102/testhost.txt
2、PHP 的解决方案
1)通过 curl 扩展实现
1 2 3 4 5 6 |
$ch = curl_init(); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host:www.studygolang.com')); curl_setopt($ch, CURLOPT_URL, 'http://192.168.1.102/testhost.txt'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $ret = curl_exec($ch); var_dump($ret); |
2)不依赖 curl 扩展的方式
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Create a stream $opts = array( 'http'=>array( 'method'=>"GET", 'header'=>"Host:www.studygolang.com" ) ); $context = stream_context_create($opts); // Open the file using the HTTP headers set above $ret = file_get_contents('http://192.168.1.102/testhost.txt', false, $context); var_dump($ret); |
3、Golang 的解决方案
由于 Go 标准库实现了 http 协议,在 net/http 包中寻找解决方案。
一般的,请求一个 url,我们通过以下代码实现:
1 |
http.Get(url) |
然而,针对本文说到的这种情况,无论 url = “http://192.168.1.102/testhost.txt” 还是 url = “http://www.studygolang.com/testhost.txt”,都无法请求到资源(没有绑定 host 的情况)。
在 http 包中的 Request 结构中,有一个字段:Host,我们可以参考上面两种解决方案,设置 Host 的值。方法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package main import ( "net/http" "io/ioutil" "fmt" ) func main() { req, err := http.NewRequest("GET", "http://192.168.1.102/testhost.txt", nil) if err != nil { panic(err) } req.Host = "www.studygolang.com" resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { panic(err) } fmt.Println(string(body)) } |
4、总结
不管是什么方式、什么语言,归根结底,需要告知服务器请求的是哪个 Host,这个是 HTTP 协议的 Host 头。如果不手动设置 Host 头,则会从请求的 url 中获取。
转载自:http://blog.studygolang.com/2014/02/golang_host/