从http请求函数调用TCP发送(网络包)

我是 Go 的新手 - 以下问题:我的程序收到一个 http post 请求,现在我想将数据从它转发到一个活动的 TCP 连接(该程序运行一个并行的 TCP 服务器)。在main()处理程序中注册如下: http.HandleFunc("/rcvtelegram", handleRestRequest)

因此 http-handler 函数是这样的:

func handleRestRequest(w http.ResponseWriter, r *http.Request) {}

到客户端的 TCP 连接是用一个知道的 net.Conn 对象打开的main()。所以理想情况下,我会启动一个带有 TCP 发送器函数的 go 例程,该函数侦听传入的字符串以通过 TCP 发送它。但是怎么办?对于通道,我似乎必须传递所有参数,但我在 http 处理程序函数中没有连接对象。我还想避免使 tcp 连接成为全局变量。我看到了 Observer 模式,但作为新手,它的复杂性让我感到害怕(不确定它是否解决了我的问题)。


慕森卡
浏览 169回答 2
2回答

互换的青春

使用结构类型来保存通道。在类型上实现http.Handler接口:type RestHandler struct {&nbsp; &nbsp; ch chan string}func (h *RestHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; // insert body of the handleRestRequest here.&nbsp; &nbsp; // Use h.ch <- someString to send string to connection}在您的主要功能中,为 TCP 发送方创建一个通道并在 goroutine 中启动发送方:ch := make(chan string)go tcpSender(ch)使用通道创建 *RestHandler 的值并将其注册为处理程序:http.Handle("/rcvtelegram", &RestHandler{ch:ch})

萧十郎

基于上述建议,我以这种方式构建它:type TcpHandler struct {&nbsp; &nbsp; connection net.Conn}然后定义了一个自定义的 HTTP 处理程序:func (t TcpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {...}然后将其注册到现有的 TCP 连接中main():httpTcpHandler := TcpHandler{connection: conn}mux := http.NewServeMux()mux.Handle("/rcvtelegram", httpTcpHandler)go startHttpServer(httpPort, mux)正常工作!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go