如何获取Cloud Run服务收到请求时的自定义域名?
我用Go语言基于Google Cloud Run开发智能链接服务原型,需要知道调用服务时使用的域名/主机名(比如默认的.run.app域名或已映射的自定义域名)。我创建了一个/__hitcheck检查端点,以JSON格式返回当前HTTP请求的referer、请求头和URL信息,但能显示调用域名的字段均无结果:r.URL.String()仅返回/__hitcheck,r.URL.Host为空,请求头中也找不到相关信息。请问如何区分用户是通过Cloud Run服务默认URL还是某个自定义域名调用/__hitcheck端点?
以下是编辑后的JSON返回结果:
{ "r.Header": { "Accept": [ "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9" ], "Accept-Encoding": [ "gzip, deflate, br" ], "Accept-Language": [ "en-US,en;q=0.9" ], "Cookie": [ "...some stuff..." ], "Early-Data": [ "1" ], "Forwarded": [ "for=\"MY IP\";proto=https" ], "Referer": [ "https://example.com/some-blog-post/" ], "Sec-Ch-Ua": [ "\"Google Chrome\";v=\"107\", \"Chromium\";v=\"107\", \"Not=A?Brand\";v=\"24\"" ], "Sec-Ch-Ua-Mobile": [ "?0" ], "Sec-Ch-Ua-Platform": [ "\"macOS\"" ], "Sec-Fetch-Dest": [ "document" ], "Sec-Fetch-Mode": [ "navigate" ], "Sec-Fetch-Site": [ "cross-site" ], "Sec-Fetch-User": [ "?1" ], "Traceparent": [ "some request ID" ], "Upgrade-Insecure-Requests": [ "1" ], "User-Agent": [ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36" ], "X-Cloud-Trace-Context": [ "some request ID" ], "X-Forwarded-For": [ "MY IP" ], "X-Forwarded-Proto": [ "https" ] }, "r.Referer()": "https://example.com/some-blog-post/", "r.RequestURI": "/__hitcheck", "r.URL": { "Scheme": "", "Opaque": "", "User": null, "Host": "", "Path": "/__hitcheck", "RawPath": "", "OmitHost": false, "ForceQuery": false, "RawQuery": "", "Fragment": "", "RawFragment": "" }, "r.URL.String()": "/__hitcheck" }
在Cloud Run环境中,请求会经过Google负载均衡转发至服务容器,因此r.URL.Host为空是正常现象——容器收到的请求行仅包含路径部分,不携带主机名。要获取用户实际调用的域名,可通过以下两种方式:
直接读取
r.Host字段
Go的*http.Request对象的Host字段对应请求的Host头,该头会由Cloud Run负载均衡正确传递,无论用户使用默认.run.app域名还是自定义域名。例如用户访问https://my-service-abc123.run.app/__hitcheck时,r.Host会返回my-service-abc123.run.app;若使用自定义域名https://links.example.com/__hitcheck,则返回links.example.com。备选:检查
X-Forwarded-Host请求头
若额外配置了自定义反向代理,负载均衡可能会设置X-Forwarded-Host头,值为用户实际访问的域名。不过标准Cloud Run配置下,r.Host已足够可靠,该头可作为补充备选。
修改/__hitcheck端点,添加对r.Host的返回即可查看用户调用的域名,示例代码片段:
func hitCheckHandler(w http.ResponseWriter, r *http.Request) { response := map[string]interface{}{ "r.Host": r.Host, // 保留你需要返回的其他字段 } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(response) }
内容的提问来源于stack exchange,提问作者Lazhar

