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 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动