宝塔服务器面板,一键全能部署及管理,送你10850元礼包,点我领取

这篇文章主要为大家展示了“Go代码中怎么绑定Host”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“Go代码中怎么绑定Host”这篇文章吧。

本文示例:

IP:192.168.1.102,也就是说需要访问这台机器上的资源

域名:studygolang.com,nginx 配置的虚拟主机

url path:/testhost.txt,内容是:Welcome to studygolang.com

需求:需要请求服务器上的 testhost.txt 资源。

1、Linux Shell 的解决方案

Linux 下的 curl 程序可以绑定 host,因此,在 shell 中可以很简单的实现,如:curl -H “Host:studygolang.com” http://192.168.1.102/testhost.txt。

2、PHP 的解决方案

1)通过 curl 扩展实现

$ch = curl_init);
curl_setopt$ch, CURLOPT_HTTPHEADER, array'Host: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 扩展的方式

// Create a stream$opts = array
   'http'=>array
       'method'=>"GET",
       'header'=>"Host: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,我们通过以下代码实现:

http.Geturl)

然而,针对本文说到的这种情况,无论 url = “http://192.168.1.102/testhost.txt” 还是 url = “http://studygolang.com/testhost.txt”,都无法请求到资源没有绑定 host 的情况)。

在 http 包中的 Request 结构中,有一个字段:Host,我们可以参考上面两种解决方案,设置 Host 的值。方法如下:

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 {
       panicerr)
   }
   req.Host = "studygolang.com"   resp, err := http.DefaultClient.Doreq)
   if err != nil {
       panicerr)
   }
   defer resp.Body.Close)
   body, err := ioutil.ReadAllresp.Body)
   if err != nil {
       panicerr)
   }
   fmt.Printlnstringbody))
}