add .Hijack() to ResponseWriter

This commit is contained in:
Zach Marcantel 2014-07-11 18:56:45 -05:00
parent 6f7c7fc4e5
commit ba422e8a40
2 changed files with 70 additions and 0 deletions

View 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
}

View File

@ -1,6 +1,9 @@
package gin
import (
"bufio"
"errors"
"net"
"net/http"
)
@ -46,3 +49,12 @@ func (w *ResponseWriter) Status() int {
func (w *ResponseWriter) WasWritten() bool {
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()
}