How to bind Host in Go code
This article mainly shows you "how to bind Host in Go code", the content is easy to understand, clear, hope to help you solve your doubts, let the editor lead you to study and learn "how to bind Host in Go code" this article.
Examples of this article:
IP:192.168.1.102, which means you need to access resources on this machine
Domain name: virtual host configured by studygolang.com,nginx
Url path:/testhost.txt, the content is: Welcome to studygolang.com
Requirements: need to request testhost.txt resources on the server.
1. The solution of Linux Shell
Curl programs under Linux can be bound to host, so it can be easily implemented in shell, such as curl-H "Host:studygolang.com" http://192.168.1.102/testhost.txt.
2. The solution of PHP
1) implemented by curl extension
$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) do not rely on the way of curl extension
/ / 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. The solution of Golang
Because the Go standard library implements the http protocol, look for a solution in the net/http package.
In general, a url is requested, which is achieved by the following code:
Http.Get (url)
However, in the case mentioned in this article, no resource can be requested whether url = "http://192.168.1.102/testhost.txt" or url =" http://studygolang.com/testhost.txt" (in the case of no host bound).
In the Request structure in the http package, there is a field: Host, and we can refer to the above two solutions and set the value of Host. The methods are as follows:
Package mainimport ("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 =" 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))} above are all the contents of the article "how to bind Host in Go Code" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!