通道关闭时收到的布尔标志与 Golang 中的预期不同

Boolean flag received when channel closes is not as expected in Golang

我有一个用于重复验证的类型:

type Authorizer struct {
    requester    *Requester
    closeChannel chan error
}

func (requester *Requester) Authorize(autoClose bool) {

    // Create a new authorizer from the requester and the close-channel
    authorizer := Authorizer{
        requester:    requester,
        closeChannel: requester.closer,
    }

    // Ensure that the requester has a reference to the authorizer so we can access the
    // updated token
    requester.authorizer = &authorizer

    // Begin the authentication loop concurrently
    go authorizer.manageAuthorization()
}

func (authorizer *Authorizer) manageAuthorization() {

    for {

        select {
        case _, ok := <-authorizer.closeChannel:
            if ok {
                fmt.Printf("Closed\n")
                return // NEVER RUNS
            }
        default:
            break
        }

        fmt.Printf("Not closed\n")
        // Do inner authorization logic
    }
}

而这个 class 创建验证器并处理请求:

type Requester struct {
    authorizer   *Authorizer
    client       *http.Client
    closer       chan error
}

func NewRequester() *Requester {

    requester := Requester{
        client: new(http.Client),
        closer: make(chan error),
    }

    requester.Authorize(false)
    return &requester
}

func (requester *Requester) Close() {
    fmt.Printf("Closing...\n")
    close(requester.closer)
}

到目前为止,我的测试都通过了这段代码。但是,我在进行报道时遇到了一个有趣的问题。考虑以下片段:

// Create the test client
client := Requester{}
client.closer = make(chan error)

// Begin authentication
client.Authorize(false)

// Now, close the channel
close(client.closer)

如果我将其嵌入到测试中并尝试使用它 运行 代码覆盖率,我会注意到指示的行永远不会 运行s。此外,我在此处添加的调试消息显示如下:

Not closed
Not closed
Not closed
Closing...
Not closed
Not closed
Not closed

Closed 消息未在任何时候打印。那么,我在这里做错了什么?

当频道关闭时,

ok 将是 false。尝试

case _, ok := <-authorizer.closeChannel:
    if !ok {
        return // RUNS
    }