Go服务器未正确响应。

huangapple go评论84阅读模式
英文:

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 !

huangapple
  • 本文由 发表于 2013年5月29日 20:31:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/16813968.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定