github.com/searKing/golang/go@v1.2.117/net/tcp/mux.go (about) 1 // Copyright 2020 The searKing Author. 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 tcp 6 7 import ( 8 "bufio" 9 "io" 10 "net" 11 "sync" 12 ) 13 14 type ServeMux struct { 15 mu sync.RWMutex 16 h Handler 17 } 18 19 // NewServeMux allocates and returns a new ServeMux. 20 func NewServeMux() *ServeMux { 21 return &ServeMux{} 22 } 23 24 // DefaultServeMux is the default ServeMux used by Serve. 25 var DefaultServeMux = &defaultServeMux 26 27 var defaultServeMux ServeMux 28 29 func (mux *ServeMux) OnOpen(conn net.Conn) error { 30 return mux.h.OnOpen(conn) 31 } 32 33 func (mux *ServeMux) OnMsgRead(r io.Reader) (req any, err error) { 34 return mux.h.OnMsgRead(r) 35 } 36 37 func (mux *ServeMux) OnMsgHandle(w io.Writer, msg any) error { 38 return mux.h.OnMsgHandle(w, msg) 39 } 40 func (mux *ServeMux) OnClose(w io.Writer, r io.Reader) error { 41 return mux.h.OnClose(w, r) 42 } 43 func (mux *ServeMux) OnError(w io.Writer, r io.Reader, err error) error { 44 return mux.h.OnError(w, r, err) 45 } 46 func (mux *ServeMux) Handle(handler Handler) { 47 mux.mu.Lock() 48 defer mux.mu.Unlock() 49 if handler == nil { 50 panic("tcp: nil handler") 51 } 52 mux.h = handler 53 } 54 func (mux *ServeMux) handle() Handler { 55 mux.mu.RLock() 56 defer mux.mu.RUnlock() 57 if mux.h == nil { 58 return NotFoundHandler() 59 } 60 return mux.h 61 } 62 func NotFoundHandler() Handler { return &NotFound{} } 63 64 var _ Handler = (*NotFound)(nil) 65 66 type NotFound struct { 67 NopServer 68 } 69 70 func (notfound *NotFound) ReadMsg(b *bufio.Reader) (msg any, err error) { 71 return nil, ErrNotFound 72 } 73 func (notfound *NotFound) HandleMsg(b *bufio.Writer, msg any) error { 74 return ErrServerClosed 75 }