Source file src/net/http/async_test.go

     1  // Copyright 2024 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package http_test
     6  
     7  import (
     8  	"errors"
     9  	"internal/synctest"
    10  )
    11  
    12  var errStillRunning = errors.New("async op still running")
    13  
    14  type asyncResult[T any] struct {
    15  	donec chan struct{}
    16  	res   T
    17  	err   error
    18  }
    19  
    20  // runAsync runs f in a new goroutine.
    21  // It returns an asyncResult which acts as a future.
    22  //
    23  // Must be called from within a synctest bubble.
    24  func runAsync[T any](f func() (T, error)) *asyncResult[T] {
    25  	r := &asyncResult[T]{
    26  		donec: make(chan struct{}),
    27  	}
    28  	go func() {
    29  		defer close(r.donec)
    30  		r.res, r.err = f()
    31  	}()
    32  	synctest.Wait()
    33  	return r
    34  }
    35  
    36  // done reports whether the function has returned.
    37  func (r *asyncResult[T]) done() bool {
    38  	_, err := r.result()
    39  	return err != errStillRunning
    40  }
    41  
    42  // result returns the result of the function.
    43  // If the function hasn't completed yet, it returns errStillRunning.
    44  func (r *asyncResult[T]) result() (T, error) {
    45  	select {
    46  	case <-r.donec:
    47  		return r.res, r.err
    48  	default:
    49  		var zero T
    50  		return zero, errStillRunning
    51  	}
    52  }
    53  

View as plain text