go 基于不同Host访问不同服务

不同于其他语言,go语言通过request.Host字段来指定主机域名,而不是headers里面"Host"。
在Nginx中,server_name对应http请求中的Host。

docker run --network host -d nginx:1.23
# 修改配置文件
vim /etc/nginx/conf.d/default.conf

package main

import (
	"fmt"
	"io"
	"net/http"
)

func main() {
    // 192.168.11.110是Nginx ip
	req, err := http.NewRequest("GET", "http://192.168.11.110:80/index.html", nil)
    req.Host = "baidu"
	if err != nil {
		fmt.Printf("new request failed, err is %v\n", err)
		return
	}

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Printf("req failed, err is %v", err)
		return
	}
	defer resp.Body.Close()

	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("get resp failed, err is %v", err)
		return
	}
	fmt.Println(string(respBody))
}

curl -H "Host: baidu" http://192.168.11.110:80/index.html

 

posted on 2025-06-07 17:31  王景迁  阅读(21)  评论(0)    收藏  举报

导航