我刚刚接触 Golang 中的 Web 应用程序。
这是作为起点的简单代码:
package main
import (
"fmt"
"log"
"net/http"
)
const (
CONN_HOST = "localhost"
CONN_PORT = "8080"
)
func helloWorld(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello World!")
}
func main() {
http.HandleFunc("/", helloWorld)
err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, nil)
if err != nil {
log.Fatal("error starting http server : ", err)
return
}
}
执行:
go run http-server.go
curl http://localhost:8080/
Hello World!
但是在网络浏览器中打开时,IP 地址:
http://111.111.1.1:8080/
connection didn't succeed
如果我替换这段代码:
err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, nil)
if err != nil {
log.Fatal("error starting http server : ", err)
return
}
与:
log.Fatal(http.ListenAndServe(":8080", nil))
所以 main() 函数仅由这两行组成:
func main() {
http.HandleFunc("/", helloWorld)
}
curl http://localhost:8080/
Hello World!
在网络浏览器中:
http://111.111.1.1:8080/
Hello World!
那么....如何使原始的简单 http-server.go 在网络浏览器中工作,而不仅仅是使用命令行curl? 期待您的好意帮助。 马可
你的服务器监听的IP地址是
localhost
,所以它只处理对localhost
的请求。
你可以尝试
curl http://111.111.1.1:8080/
,你也会失败的。
如果您想从 LAN 或任何其他 IP 访问您的服务器,您应该设置
CONN_HOST = "111.111.1.1"。