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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。