douxian9943 2017-10-12 01:06
浏览 43
已采纳

在net.Conn上创建一个http响应编写器

In the following code:

l, err := net.Listen("tcp", ":"+port)
assert(err)
c, err := l.Accept()
assert(err)
cert, err := tls.LoadX509KeyPair(TLS_CERT, TLS_PKEY)
assert(err)
TLSconfig := &tls.Config{
    Certificates: []tls.Certificate{cert},
    ClientAuth:   tls.VerifyClientCertIfGiven,
    ServerName:   DOMAIN_NAME,
}
tlsConn := tls.Server(c, TLSconfig)
tlsConn.Handshake()
c = net.Conn(tlsConn)

I would like to create an http response writer, e.g.:

w := CreateResponseWriter(c)  //<-- how to do this?
w.Header().Set(...)
if !Authorized(c.RemoteAddr()) {
    http.Error(w, "Unauthorized", http.StatusUnauthorized)
    return
}
data, _ := os.Open("/path/to/content")
defer data.Close()
io.Copy(w, data)

The purpose is that I am writing an http proxy in Golang, I will need to check if the remote connection is authorized or not, if not, I will show the login page. Thanks.

  • 写回答

1条回答 默认 最新

  • duangangpin078794 2017-10-12 08:15
    关注

    http.ResponseWriter is an interface. So to create your own, just make any data type that satisfies the interface.

    But it looks like what you're really trying to do is just bind your HTTP server to an existing connection. For that you can use the Serve or ServeTLS methods.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog