首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检查go服务器中是否劫持了http连接。

检查go服务器中是否劫持了http连接。
EN

Stack Overflow用户
提问于 2022-09-30 08:05:29
回答 1查看 61关注 0票数 1

我正在用Go编写一个HTTP服务器,它使用以下模式来处理API输出:

代码语言:javascript
复制
func handler(w http.ResponsWriter, r *http.Request) {
    defer reply(w, r, L)() //L is a Logger
    //do things...
}

func reply(w http.ResponseWriter, r *http.Request, log Logger) func() {
    cid := []byte{0, 0, 0, 0}
    if log != nil {
        rand.Read(cid)
        log.Debug("[%x] %s %s", cid, r.Method, r.URL.String())
    }
    entry := time.Now()
    return func() {
        if log != nil {
            defer log.Debug("[%x] elapsed %d millis", cid, time.Since(entry).Milliseconds())
        }
        _, err := w.Write(nil)
        if err == http.ErrHijacked {
            return //API is a WEBSOCKET entry point, do nothing
        }
        //handle common output logic for normal HTTP APIs...
    }
}

我之所以这样做,是因为我在标准库中找到了这样的评论:

代码语言:javascript
复制
// ErrHijacked is returned by ResponseWriter.Write calls when
// the underlying connection has been hijacked using the
// Hijacker interface. A zero-byte write on a hijacked
// connection will return ErrHijacked without any other side
// effects.
ErrHijacked = errors.New("http: connection has been hijacked")

但是,在Write()方法之后,我得到了以下注释:

代码语言:javascript
复制
// Write writes the data to the connection as part of an HTTP reply.
//
// If WriteHeader has not yet been called, Write calls
// WriteHeader(http.StatusOK) before writing the data. If the Header
// does not contain a Content-Type line, Write adds a Content-Type set
// to the result of passing the initial 512 bytes of written data to
// ...
Write([]byte) (int, error)

我的问题是:

  1. 是否可以使用我的代码来安全地检测一个HTTP连接是否被劫持?我只想检查连接是否被劫持,但是 not 想让它为我添加头吗!

由于

  1. 是一个接口,所以我无法通过源代码单击来了解标准库是如何实现该方法的。通常,我如何深入到标准库(或任何开放源代码)来查找接口的实现?
EN

回答 1

Stack Overflow用户

发布于 2022-09-30 13:19:20

多亏了Cerise,我找到了标准response.Writer的源代码:

代码语言:javascript
复制
func (w *response) write(lenData int, dataB []byte, dataS string) (n int, err error) {
    if w.conn.hijacked() {
        if lenData > 0 {
            caller := relevantCaller()
            w.conn.server.logf("http: response.Write on hijacked connection from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
        }
        return 0, ErrHijacked
    }
    ... ....

因此,正如文件中所说的,没有副作用。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73905718

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档