doulian4762 2015-12-22 05:08
浏览 31

Golang嵌入具有其他隐藏方法的接口吗?

I want to embed a http.ResponseWriter in a struct. That's fine, it makes sure my struct also implements http.ResponseWriter:

type MyWriter struct {
    BytesWritten int
    http.ResponseWriter
}

However, it no longer implements http.Hijacker, http.CloseNotifier or http.Flusher even though the embedded http.ResponseWriter usually does.

Is there some way to do this?

  • 写回答

2条回答 默认 最新

  • doucheyi1347 2015-12-22 06:20
    关注

    If you know that the response writer satisfies all of the interfaces listed in the question, then you can do this:

    type allResponseWriterInterfaces {
        http.ResponseWriter
        http.Hijacker
        http.CloseNotifier
        http.Flusher
    }
    
    type MyWriter struct {
        BytesWritten int
        allResponseWriterInterfaces
    }
    
    ...
    
    aw, ok := w.(allResponseWriterInterfaces)
    if !ok {
        // oops, response writer does not implement the interfaces
        // handle the error
    }
    mw := MyWriter{0, aw}
    

    It get's messy if the response writer does not satisfy all of the interfaces. See the Gorilla logger for an example of handling the case where the response writer satisfies (http.ResponseWriter, http.CloseNotifier) or (http.ResponseWriter, http.CloseNotifier, http.Hijacker).

    评论

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错