我编写了一个 Go 服务器,只要您从 localhost(并寻址到 localhost)向它发送请求,它就可以完美运行,但是当您尝试从浏览器(从不同的计算机)甚至只是从浏览器访问它时,它就不起作用指向外部 IP 地址。我希望能够将它作为外部服务器访问,而不仅仅是在本地访问。为什么不能?
(精简)源代码:
package main
import (
"fmt"
"net"
"os"
)
func main() {
// Listen for incoming connections.
l, err := net.Listen("tcp", "localhost:2082")
if err != nil {
fmt.Println("Error listening:", err.Error())
os.Exit(1)
}
// Close the listener when the application closes.
defer l.Close()
for {
// Listen for an incoming connection.
_, err := l.Accept()
if err != nil {
fmt.Println("Error accepting: ", err.Error())
os.Exit(1)
}
fmt.Println("Incoming connection")
}
}
Run Code Online (Sandbox Code Playgroud)
当你curl localhost:2082
,它说“传入连接”。
当你时curl mydomain.com:2082
,它什么都不做。
端口被转发。我确信这一点,因为我从那个端口运行了一个 (node.js) web 服务器,它运行良好。如果相关,我将在 Amazon EC2 实例上的 Ubuntu 12.04 上运行。
我很感激任何帮助。谢谢!
侦听任何传入 IP(不仅仅是localhost
,默认映射到 127.0.0.1)的一种方法是:
net.Listen("tcp", ":2082")
Run Code Online (Sandbox Code Playgroud)
你也有这个功能net/http/#ListenAndServe
,如果你想的话,它允许你在多个特定的 ip 上触发监听。
go http.ListenAndServe("10.0.0.1:80", nil)
http.ListenAndServe("10.0.0.2:80", nil)
Run Code Online (Sandbox Code Playgroud)
一个很好的例子可以在“ Go 中的请求处理回顾”中看到。