当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


GO Hijacker用法及代码示例


GO语言"net/http"包中"Hijacker"类型的用法及代码示例。

Hijacker 接口由ResponseWriters 实现,它允许 HTTP 处理程序接管连接。

HTTP/1.x 连接的默认 ResponseWriter 支持 Hijacker,但 HTTP/2 连接故意不支持。 ResponseWriter 包装器也可能不支持劫持者。处理程序应始终在运行时测试此能力。

用法:

type Hijacker interface {
    // Hijack lets the caller take over the connection.
    // After a call to Hijack the HTTP server library
    // will not do anything else with the connection.
    //
    // It becomes the caller's responsibility to manage
    // and close the connection.
    //
    // The returned net.Conn may have read or write deadlines
    // already set, depending on the configuration of the
    // Server.It is the caller's responsibility to set
    // or clear those deadlines as needed.
    //
    // The returned bufio.Reader may contain unprocessed buffered
    // data from the client.
    //
    // After a call to Hijack, the original Request.Body must not
    // be used.The original Request's Context remains valid and
    // is not canceled until the Request's ServeHTTP method
    // returns.
    Hijack()(net.Conn, *bufio.ReadWriter, error)
}

例子:

package main

import (
	"fmt"
	"log"
	"net/http"
)

func main() {
	http.HandleFunc("/hijack", func(w http.ResponseWriter, r *http.Request) {
		hj, ok := w.(http.Hijacker)
		if !ok {
			http.Error(w, "webserver doesn't support hijacking", http.StatusInternalServerError)
			return
		}
		conn, bufrw, err := hj.Hijack()
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// Don't forget to close the connection:
		defer conn.Close()
		bufrw.WriteString("Now we're speaking raw TCP. Say hi: ")
		bufrw.Flush()
		s, err := bufrw.ReadString('\n')
		if err != nil {
			log.Printf("error reading string: %v", err)
			return
		}
		fmt.Fprintf(bufrw, "You said: %q\nBye.\n", s)
		bufrw.Flush()
	})
}

相关用法


注:本文由纯净天空筛选整理自golang.google.cn大神的英文原创作品 Hijacker。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。