将Golang中的net.Dial响应写入浏览器。

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

Golang write net.Dial response to the browser

问题

我正在使用net包进行编程,并且想要创建一个简单的代理。首先,在本地创建一个监听器,然后拨号远程地址。

remote, err := net.Dial("tcp", "google.com:80")
if err != nil {
    log.Fatal(err)
}
defer remote.Close()

fmt.Fprint(remote, "GET / HTTP/1.0\r\n\r\n")

你想要如何将响应传输到浏览器?或者我需要使用默认的Web服务器并复制响应主体吗?我真的想尝试使用net包或其他方法。

谢谢。

英文:

I am playing with the net package, and i want to make a simple proxy.
First i make a listener on localhost, then i dial the remote address

remote, err := net.Dial("tcp", "google.com:80")
if err != nil {
    log.Fatal(err)
}
defer remote.Close()

fmt.Fprint(remote, "GET / HTTP/1.0\r\n\r\n")

How can i pipe the response to the browser? Or do i need to work with the default webserver and copy the response body? I really want to try it with net package or something

thx

答案1

得分: 0

将远程连接复制使用2个goroutine和io.Copy函数。

func copyContent(from, to net.Conn, done chan bool) {
    _, err := io.Copy(from, to)
    if err != nil {
        done <- true
    }
    done <- true
}

// 在主函数中
done := make(chan bool, 2)
go copyContent(conn, remote, done)
go copyContent(remote, conn, done)
<-done
<-done

以上是要翻译的内容。

英文:

To copy the connection from the remote is used 2 goroutines with io.Copy

func copyContent(from, to net.Conn, done chan bool) {
    _, err := io.Copy(from, to)
    if err != nil {
        done &lt;- true
    }
 done &lt;- true
}

// in the main func
done := make(chan bool, 2)
go copyContent(conn, remote, done)
go copyContent(remote, conn, done)
&lt;-done
&lt;-done

huangapple
  • 本文由 发表于 2014年9月14日 18:51:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/25832482.html
匿名

发表评论

匿名网友

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

确定