go - golang http server http.ListenAndServe 仅适用于 localhost?
问题描述
我使用 golang 在 Azure Linux VM 中实现了一个 HTTP 服务器。下面是简单的 golang 服务器代码,监听 30175 端口。该端口上没有防火墙。
package main
import (
"fmt"
"log"
"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)
log.Fatal(http.ListenAndServe(":30175", nil))
}
sudo netstat -tlnp 的结果是:
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:21 0.0.0.0:* LISTEN 1605/vsftpd
tcp 0 0 127.0.0.1:3350 0.0.0.0:* LISTEN 1873/xrdp-sesman
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1697/sshd
tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN 1379/cupsd
tcp 0 0 127.0.0.1:6010 0.0.0.0:* LISTEN 4879/8
tcp 0 0 127.0.0.1:6011 0.0.0.0:* LISTEN 15507/9
tcp 0 0 0.0.0.0:3389 0.0.0.0:* LISTEN 1859/xrdp
tcp 0 0 0.0.0.0:8000 0.0.0.0:* LISTEN 2112/python
tcp6 0 0 :::22 :::* LISTEN 1697/sshd
tcp6 0 0 ::1:631 :::* LISTEN 1379/cupsd
tcp6 0 0 ::1:6010 :::* LISTEN 4879/8
tcp6 0 0 ::1:6011 :::* LISTEN 15507/9
tcp6 0 0 :::30175 :::* LISTEN 46595/HttpHandler
我只能在 localhost 中获得响应,但没有来自远程服务器的响应:
curl localhost:30175
Hi there, I love !
curl serveripaddress:30175
not working
解决方案
这与您的代码无关。这是一个典型的防火墙问题。
- 默认情况下(在 *nix 平台上)所有传入流量都被阻止并允许所有传出。您需要打开操作系统上的端口以允许传入流量到达您的服务器。尝试安装
ufw
实用程序并运行sudo ufw allow 30175
- 从问题来看,您的服务器似乎正在使用 tcp6。理想情况下,它不应该引起问题,因为 tcp6 应该同时支持 IPV4 和 IPV6。但如果有意义的话,我建议你将其降级为 tcp。
推荐阅读
- django - 我认为在一个类中使用信号更新外键与另一类的多字段
- scheme - 如何只消费 Scheme 中的第一个返回值?
- td-engine - TDengine的两个客户端相差8小时
- php - 如何使用 Codeigniter 和 Bootstrap 中的按钮对数据进行排序
- javascript - Ng If 使用布尔值 - 更改页面标题
- javascript - .click() on href javascript:void(0) 导致未定义
- php - API 平台自定义控制器返回错误 500“控制器 [名称] 既不作为服务存在也不作为类存在”
- amazon-web-services - NoSql (DynamoDB) 的简单搜索功能
- python-3.8 - AttributeError:模块 'keras.optimizers' 没有属性 'Adam'
- ios - iOS中有没有办法将WebRTC“呼叫”作为“媒体”声音播放?