mirror of
https://github.com/gin-gonic/gin.git
synced 2025-10-15 21:06:39 +08:00
add .Hijack() to ResponseWriter
This commit is contained in:
parent
6f7c7fc4e5
commit
ba422e8a40
58
examples/websocket/example_websocket.go
Normal file
58
examples/websocket/example_websocket.go
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"code.google.com/p/go.net/websocket"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
r := gin.New()
|
||||||
|
r.GET("/", func(c *gin.Context) {
|
||||||
|
handler := websocket.Handler(func(conn *websocket.Conn) {
|
||||||
|
// This is the simplest possible echoserver
|
||||||
|
//
|
||||||
|
// For a more advanced handler you can use the
|
||||||
|
// conn.Read and conn.Write methods as the
|
||||||
|
// websocket.Conn type conforms to io.Reader+io.Writer
|
||||||
|
|
||||||
|
io.Copy(conn, conn)
|
||||||
|
})
|
||||||
|
handler.ServeHTTP(&c.Writer, c.Req)
|
||||||
|
})
|
||||||
|
|
||||||
|
go r.Run(":8080")
|
||||||
|
|
||||||
|
lock := make(chan bool)
|
||||||
|
go testServer(100, lock)
|
||||||
|
<-lock
|
||||||
|
}
|
||||||
|
|
||||||
|
func testServer(count int, done chan bool) {
|
||||||
|
client, err := websocket.Dial("ws://localhost:8080", "", "http://localhost/")
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 0; i < count; i++ {
|
||||||
|
out := []byte(strconv.Itoa(i))
|
||||||
|
_, err = client.Write(out)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
fmt.Printf("Sent: %s\n", out)
|
||||||
|
|
||||||
|
var in = make([]byte, 512)
|
||||||
|
_, err = client.Read(in)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
fmt.Printf("Received: %s\n\n", in)
|
||||||
|
}
|
||||||
|
|
||||||
|
done <- true
|
||||||
|
}
|
@ -1,6 +1,9 @@
|
|||||||
package gin
|
package gin
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bufio"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -46,3 +49,12 @@ func (w *ResponseWriter) Status() int {
|
|||||||
func (w *ResponseWriter) WasWritten() bool {
|
func (w *ResponseWriter) WasWritten() bool {
|
||||||
return w.status == StatusUnset
|
return w.status == StatusUnset
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// allow connection hijacking
|
||||||
|
func (w *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
||||||
|
hijacker, ok := w.ResponseWriter.(http.Hijacker)
|
||||||
|
if !ok {
|
||||||
|
return nil, nil, errors.New("the ResponseWriter doesn't support the Hijacker interface")
|
||||||
|
}
|
||||||
|
return hijacker.Hijack()
|
||||||
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user