我按照 Go 文档上的示例并为 Go 服务器编译了以下代码:
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
Run Code Online (Sandbox Code Playgroud)
但是当我访问 localhost:8080 时,它没有显示任何内容。
改变http.ListenAndServe(":8080", nil)
到
if err := http.ListenAndServe("localhost:8080", nil); err != nil {
log.Fatal("ListenAndServe: ", err)
}
Run Code Online (Sandbox Code Playgroud)
这将强制服务器仅侦听接口localhost,并且您不会遇到权限和防火墙规则的问题。它还记录您可能遇到的任何错误。
| 归档时间: |
|
| 查看次数: |
4333 次 |
| 最近记录: |