Go 服务器未正确响应。

Hic*_*ick 1 go

我按照 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 时,它没有显示任何内容。

Int*_*net 5

改变http.ListenAndServe(":8080", nil)

if err := http.ListenAndServe("localhost:8080", nil); err != nil {
    log.Fatal("ListenAndServe: ", err)
}
Run Code Online (Sandbox Code Playgroud)

这将强制服务器仅侦听接口localhost,并且您不会遇到权限和防火墙规则的问题。它还记录您可能遇到的任何错误。