diff options
author | Aliaksandr Valialkin <valyala@gmail.com> | 2015-11-29 23:40:02 +0200 |
---|---|---|
committer | Aliaksandr Valialkin <valyala@gmail.com> | 2015-11-29 23:40:02 +0200 |
commit | c74b2d8d7e8c54b03f1e82e6483039c68ec5d0fe (patch) | |
tree | 38eef0ec3f453a3713dd12c9fdfdc23a94e93974 /server_example_test.go | |
parent | Added initial server examples (diff) | |
download | fasthttp-c74b2d8d7e8c54b03f1e82e6483039c68ec5d0fe.tar.gz fasthttp-c74b2d8d7e8c54b03f1e82e6483039c68ec5d0fe.tar.bz2 fasthttp-c74b2d8d7e8c54b03f1e82e6483039c68ec5d0fe.zip |
Added an example for RequestCtx.Hijack
Diffstat (limited to 'server_example_test.go')
-rw-r--r-- | server_example_test.go | 38 |
1 files changed, 38 insertions, 0 deletions
diff --git a/server_example_test.go b/server_example_test.go index 9f6d9f3..f0bb2b0 100644 --- a/server_example_test.go +++ b/server_example_test.go @@ -81,3 +81,41 @@ func ExampleServer() { log.Fatalf("error in ListenAndServe: %s", err) } } + +func ExampleRequestCtx_Hijack() { + // hijackHandler is called on hijacked connection. + hijackHandler := func(c net.Conn) { + fmt.Fprintf(c, "This message is sent over a hijacked connection to the client %d\n", c.RemoteAddr()) + fmt.Fprintf(c, "Send me something and I'll echo it to you\n") + var buf [1]byte + for { + if _, err := c.Read(buf[:]); err != nil { + log.Printf("error when reading from hijacked connection: %s", err) + return + } + fmt.Fprintf(c, "You sent me %q. Waiting for new data\n", buf[:]) + } + } + + // requestHandler is called for each incoming request. + requestHandler := func(ctx *RequestCtx) { + path := ctx.Path() + switch { + case string(path) == "/hijack": + // Note that the connection is hijacked only after + // returning from requestHandler and sending http response. + ctx.Hijack(hijackHandler) + + // The connection will be hijacked after sending this response. + fmt.Fprintf(ctx, "Hijacked the connection!") + case string(path) == "/": + fmt.Fprintf(ctx, "Root directory requested") + default: + fmt.Fprintf(ctx, "Requested path is %q", path) + } + } + + if err := ListenAndServe(":80", requestHandler); err != nil { + log.Fatalf("error in ListenAndServe: %s", err) + } +} |