Пример #1
0
func ExampleWithTimeout() {
	// Pass a context with a timeout to tell a blocking function that it
	// should abandon its work after the timeout elapses.
	ctx, _ := context.WithTimeout(context.Background(), 100*time.Millisecond)
	select {
	case <-time.After(200 * time.Millisecond):
		fmt.Println("overslept")
	case <-ctx.Done():
		fmt.Println(ctx.Err()) // prints "context deadline exceeded"
	}
	// Output:
	// context deadline exceeded
}
Пример #2
0
func (s *server) handleRequest(w http.ResponseWriter, r *http.Request) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	ctx = newContext(ctx, r)

	switch r.Method {
	case "GET":
		s.playbackStream(ctx, w, r)
	case "POST":
		s.recordStream(ctx, w, r)
	case "DELETE":
		s.deleteStream(ctx, w, r)
	}
}
Пример #3
0
func TestCancelIn(t *testing.T) {
	r, _ := io.Pipe()
	rConn, nConn := redisPipeConn()

	s := &Stream{
		conn: rConn,
		ctx:  context.Background(),
		Name: "canceled-in-stream",
		done: make(chan struct{}),
	}

	go streamIn(s, r)

	s.Cancel()

	if s.Err != nil {
		t.Error(s.Err)
	}

	_, err := nConn.Read([]byte{})
	if err == nil {
		t.Error("Conn was not closed by Cancel()")
	}
}
Пример #4
0
func TestCancelOut(t *testing.T) {
	_, w := io.Pipe()
	rConn, nConn := redisPipeConn()

	s := &Stream{
		conn: rConn,
		ctx:  context.Background(),
		Name: "canceled-out-stream",
		done: make(chan struct{}),
	}

	go streamOut(s, w)

	s.Cancel()

	if s.Err != nil {
		t.Error(s.Err)
	}

	_, err := nConn.Write([]byte("write on closed connection"))
	if err == nil {
		t.Error("Conn was not closed by Cancel()")
	}
}