Go语言部署的Cloud Function访问robots.txt返回404问题求助
问题原因说明
Cloud Function本身没有限制robots.txt的访问服务,你遇到的404问题是代码逻辑缺失导致的,和平台无关:
- 所有发往Cloud Function触发器的请求,无论路径是什么,都会被转发到你指定的入口函数
HelloWorld处理,平台不会自动识别静态文件并返回,你需要自己实现路径判断和文件读取逻辑 - 你当前的代码没有对请求路径做任何判断,也没有读取robots.txt文件的逻辑,自然无法返回对应内容
修复方案
你只需要修改Function.go的逻辑,增加路径判断和静态文件读取的逻辑即可,修改后参考代码如下:
// Package p contains an HTTP Cloud Function. package p import ( "encoding/json" "fmt" "html" "io" "log" "net/http" "os" ) // HelloWorld prints the JSON encoded "message" field in the body // of the request or "Hello, World!" if there isn't one. func HelloWorld(w http.ResponseWriter, r *http.Request) { // 新增robots.txt路径处理逻辑 if r.URL.Path == "/robots.txt" { content, err := os.ReadFile("robots.txt") if err != nil { http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) return } w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.Write(content) return } var d struct { Message string `json:"message"` } if err := json.NewDecoder(r.Body).Decode(&d); err != nil { switch err { case io.EOF: fmt.Fprint(w, "Hello World!") return default: log.Printf("json.NewDecoder: %v", err) http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) return } } if d.Message == "" { fmt.Fprint(w, "Hello World!") return } fmt.Fprint(w, html.EscapeString(d.Message)) }
如果你后续需要支持更多静态文件,可以统一加路径映射逻辑,不需要单独为每个文件写判断。如果robots.txt内容不会经常变动,也可以直接把内容硬编码在代码里,省去读文件的步骤。
内容的提问来源于stack exchange,提问作者GyeongSik Jang
相关产品推荐
相关产品推荐

