| 1 | // Copyright 2017 fatedier, fatedier@gmail.com |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package net |
| 16 | |
| 17 | import ( |
| 18 | "fmt" |
| 19 | "net" |
| 20 | "sync" |
| 21 | |
| 22 | "github.com/fatedier/golib/errors" |
| 23 | ) |
| 24 | |
| 25 | // InternalListener is a listener that can be used to accept connections from |
| 26 | // other goroutines. |
| 27 | type InternalListener struct { |
| 28 | acceptCh chan net.Conn |
| 29 | closed bool |
| 30 | mu sync.Mutex |
| 31 | } |
| 32 | |
| 33 | func NewInternalListener() *InternalListener { |
| 34 | return &InternalListener{ |
| 35 | acceptCh: make(chan net.Conn, 128), |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | func (l *InternalListener) Accept() (net.Conn, error) { |
| 40 | conn, ok := <-l.acceptCh |
| 41 | if !ok { |
| 42 | return nil, fmt.Errorf("listener closed") |
| 43 | } |
| 44 | return conn, nil |
| 45 | } |
| 46 | |
| 47 | func (l *InternalListener) PutConn(conn net.Conn) error { |
| 48 | err := errors.PanicToError(func() { |
| 49 | select { |
| 50 | case l.acceptCh <- conn: |
| 51 | default: |
| 52 | conn.Close() |
| 53 | } |
| 54 | }) |
| 55 | if err != nil { |
| 56 | return fmt.Errorf("put conn error: listener is closed") |
| 57 | } |
| 58 | return nil |
| 59 | } |
| 60 | |
| 61 | func (l *InternalListener) Close() error { |
| 62 | l.mu.Lock() |
| 63 | defer l.mu.Unlock() |
| 64 | if !l.closed { |
| 65 | close(l.acceptCh) |
| 66 | l.closed = true |
| 67 | } |
| 68 | return nil |
| 69 | } |
| 70 | |
| 71 | func (l *InternalListener) Addr() net.Addr { |
| 72 | return &InternalAddr{} |
| 73 | } |
| 74 | |
| 75 | type InternalAddr struct{} |
| 76 | |
| 77 | func (ia *InternalAddr) Network() string { |
| 78 | return "internal" |
| 79 | } |
| 80 | |
| 81 | func (ia *InternalAddr) String() string { |
| 82 | return "internal" |
| 83 | } |