github.com/searKing/golang/go@v1.2.74/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 "github.com/searKing/golang/go/util/object" 14 ) 15 16 type ServeMux struct { 17 mu sync.RWMutex 18 h Handler 19 } 20 21 // NewServeMux allocates and returns a new ServeMux. 22 func NewServeMux() *ServeMux { 23 return &ServeMux{} 24 } 25 26 // DefaultServeMux is the default ServeMux used by Serve. 27 var DefaultServeMux = &defaultServeMux 28 29 var defaultServeMux ServeMux 30 31 func (mux *ServeMux) OnOpen(conn net.Conn) error { 32 return mux.h.OnOpen(conn) 33 } 34 35 func (mux *ServeMux) OnMsgRead(r io.Reader) (req interface{}, err error) { 36 return mux.h.OnMsgRead(r) 37 } 38 39 func (mux *ServeMux) OnMsgHandle(w io.Writer, msg interface{}) error { 40 return mux.h.OnMsgHandle(w, msg) 41 } 42 func (mux *ServeMux) OnClose(w io.Writer, r io.Reader) error { 43 return mux.h.OnClose(w, r) 44 } 45 func (mux *ServeMux) OnError(w io.Writer, r io.Reader, err error) error { 46 return mux.h.OnError(w, r, err) 47 } 48 func (mux *ServeMux) Handle(handler Handler) { 49 mux.mu.Lock() 50 defer mux.mu.Unlock() 51 object.RequireNonNil(handler, "tcp: nil handler") 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 // NotFoundHandler returns a simple request handler 65 // that replies to each request with a ``404 page not found'' reply. 66 type NotFound struct { 67 Handler 68 NopServer 69 } 70 71 func (notfound *NotFound) ReadMsg(b *bufio.Reader) (msg interface{}, err error) { 72 return nil, ErrNotFound 73 } 74 func (notfound *NotFound) HandleMsg(b *bufio.Writer, msg interface{}) error { 75 return ErrServerClosed 76 }