部署Go服务器到Heroku/Render后出现404页面未找到问题求助
排查Go HTTP服务器部署到Heroku/Render后404问题
访问路径不匹配:你的代码仅注册了
/hellohng路由,本地运行时你访问的是http://localhost:9090/hellohng,但部署到平台后,若直接访问域名根路径(比如https://your-app.herokuapp.com/),会因为根路径/没有对应的处理逻辑返回404。必须访问完整路径https://your-app.herokuapp.com/hellohng才能获取预期的JSON响应。添加根路径处理(可选优化):如果希望访问根路径时能得到引导提示,可在main函数中补充根路径的路由处理,示例如下:
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) fmt.Fprintf(w, "请访问 /hellohng 获取JSON响应") // 也可以设置重定向: // http.Redirect(w, r, "/hellohng", http.StatusPermanentRedirect) })
- 端口配置无问题:你的代码已正确读取平台提供的
PORT环境变量,Heroku和Render会自动设置该变量,这部分无需额外调整。
修改后的完整代码示例
package main import ( "encoding/json" "fmt" "log" "net/http" "os" ) type helloHngResponse struct{ SlackUsername string `json:"SlackUsername"` Backend bool `json:"Backend"` Age int `json:"Age"` Bio string `json:"Bio"` } func helloHng(w http.ResponseWriter, r *http.Request){ response := helloHngResponse{SlackUsername: "kodeforce98", Backend: true, Age: 24, Bio: "Proud firstborn, Golang Developer, Committed christian, Faithful boyfriend"} encoder := json.NewEncoder(w) encoder.Encode(response) } func main(){ port := os.Getenv("PORT") if port == ""{ port = "9090" } // 新增根路径引导 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "请访问 /hellohng 获取JSON响应") }) http.HandleFunc("/hellohng", helloHng) log.Printf("Server starting on port %v\n", port) log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", port), nil)) }
内容的提问来源于stack exchange,提问作者Kodeforce
相关产品推荐
相关产品推荐

