diff options
author | Aliaksandr Valialkin <valyala@gmail.com> | 2015-11-30 00:14:57 +0200 |
---|---|---|
committer | Aliaksandr Valialkin <valyala@gmail.com> | 2015-11-30 00:14:57 +0200 |
commit | b501c24a98a96381e90a60096bf405d061f475f6 (patch) | |
tree | 6c1dc249c07476e723ff08488dee0e4f197a6bc4 /server_example_test.go | |
parent | Added an example for RequestCtx.Hijack (diff) | |
download | fasthttp-b501c24a98a96381e90a60096bf405d061f475f6.tar.gz fasthttp-b501c24a98a96381e90a60096bf405d061f475f6.tar.bz2 fasthttp-b501c24a98a96381e90a60096bf405d061f475f6.zip |
Added an example for RequestCtx.TimeoutError
Diffstat (limited to 'server_example_test.go')
-rw-r--r-- | server_example_test.go | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/server_example_test.go b/server_example_test.go index f0bb2b0..a87f3b1 100644 --- a/server_example_test.go +++ b/server_example_test.go @@ -3,7 +3,9 @@ package fasthttp import ( "fmt" "log" + "math/rand" "net" + "time" ) func ExampleListenAndServe() { @@ -119,3 +121,34 @@ func ExampleRequestCtx_Hijack() { log.Fatalf("error in ListenAndServe: %s", err) } } + +func ExampleRequestCtx_TimeoutError() { + requestHandler := func(ctx *RequestCtx) { + // Emulate long-running task, which touches ctx. + doneCh := make(chan struct{}) + go func() { + workDuration := time.Millisecond * time.Duration(rand.Intn(2000)) + time.Sleep(workDuration) + + fmt.Fprintf(ctx, "ctx has been accessed by long-running task\n") + fmt.Fprintf(ctx, "The reuqestHandler may be finished by this time.\n") + + close(doneCh) + }() + + select { + case <-doneCh: + fmt.Fprintf(ctx, "The task has been finished in less than a second") + case <-time.After(time.Second): + // Since the long-running task is still running and may access ctx, + // we must call TimeoutError before returning from requestHandler. + // + // Otherwise our program will suffer from data races. + ctx.TimeoutError("Timeout!") + } + } + + if err := ListenAndServe(":80", requestHandler); err != nil { + log.Fatalf("error in ListenAndServe: %s", err) + } +} |