-
Notifications
You must be signed in to change notification settings - Fork 9
/
listener.go
60 lines (51 loc) · 1.13 KB
/
listener.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package grpcstdio
import (
"context"
"errors"
"net"
"sync"
)
var ErrListenerClosed = errors.New("listener was closed")
func NewListener(ctx context.Context) *StdinListener {
return &StdinListener{ctx: ctx, ch: make(chan net.Conn)}
}
type StdinListener struct {
ctx context.Context
ch chan net.Conn
mu sync.Mutex
closed bool
}
func (lis *StdinListener) Ready(ctx context.Context, conn net.Conn) error {
select {
case lis.ch <- conn:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (lis *StdinListener) Accept() (net.Conn, error) {
select {
case conn, ok := <-lis.ch:
if !ok {
return nil, ErrListenerClosed
}
return conn, nil
case <-lis.ctx.Done():
return nil, lis.ctx.Err()
}
}
func (lis *StdinListener) Close() error {
lis.mu.Lock()
if !lis.closed {
close(lis.ch)
lis.closed = true
}
lis.mu.Unlock()
return nil
}
func (lis *StdinListener) Addr() net.Addr {
return stdioAddr{"stdio", "listener"}
}