英文:
Go server not responding properly.
问题
我按照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时,没有显示任何内容。
英文:
I followed the example on Go docs and compiled this code for a Go server:
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)
}
But when I access
localhost:8080 it doesn't show up anything.
答案1
得分: 4
更改 http.ListenAndServe(":8080", nil)
为
if err := http.ListenAndServe("localhost:8080", nil); err != nil {
log.Fatal("ListenAndServe: ", err)
}
这将强制服务器仅监听 localhost
接口,您将不会遇到权限和防火墙规则的问题。它还会记录您可能遇到的任何错误。
英文:
Change http.ListenAndServe(":8080", nil)
to
if err := http.ListenAndServe("localhost:8080", nil); err != nil {
log.Fatal("ListenAndServe: ", err)
}
This will force the server to only listen on the localhost
interface and you won't have problems with permissions and firewall rules. It also logs any errors you may encounter.
答案2
得分: -1
在Linux中,您需要权限来运行程序,因为它需要监听8080端口。
我正在使用Ubuntu,并运行go build -o main
,然后运行sudo ./main
,当我访问localhost:8080时,它显示Hi there, I love !
英文:
In linux you need permission to run the program, because it is need listen on 8080 port.
I am using Ubuntu, and I ran go build -o main
, then I run sudo ./main
, when I access the localhost:8080 it shows Hi there, I love !
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论