1

我按照 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)
}

但是当我访问 localhost:8080 时,它什么也没显示。

4

2 回答 2

4

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

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

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

于 2013-05-29T23:43:53.353 回答
-1

在 linux 中你需要权限才能运行程序,因为它需要监听 8080 端口。我正在使用 Ubuntu,go build -o main然后运行,然后运行sudo ./main,当我访问 localhost:8080 时,它显示Hi there, I love !

于 2013-05-29T14:21:57.830 回答