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()
})
}
相关用法
- GO HandleFunc用法及代码示例
- GO HasPrefix用法及代码示例
- GO HTMLEscape用法及代码示例
- GO Handle用法及代码示例
- GO HasSuffix用法及代码示例
- GO PutUvarint用法及代码示例
- GO Scanner.Scan用法及代码示例
- GO LeadingZeros32用法及代码示例
- GO NewFromFiles用法及代码示例
- GO Regexp.FindString用法及代码示例
- GO Time.Sub用法及代码示例
- GO Regexp.FindAllIndex用法及代码示例
- GO Encode用法及代码示例
- GO ResponseRecorder用法及代码示例
- GO Value用法及代码示例
- GO StreamWriter用法及代码示例
- GO Fscanln用法及代码示例
- GO Values.Get用法及代码示例
- GO NumError用法及代码示例
- GO TrailingZeros8用法及代码示例
注:本文由纯净天空筛选整理自golang.google.cn大神的英文原创作品 Hijacker。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。