interface rewriting inspired by gorpc

This commit is contained in:
Matthias Fulz 2020-02-19 01:36:18 +01:00
parent da05b60694
commit b097952eb1
4 changed files with 71 additions and 5 deletions

View File

@ -90,3 +90,13 @@ func NewClient(conn net.Conn) *Client {
return ret
}
type DialFunc func(addr string) (conn io.ReadWriteCloser, err error)
func unixDial(addr string) (conn io.ReadWriteCloser, err error) {
if conn, err = net.Dial("unix", addr); err != nil {
return nil, err
}
return conn, nil
}

13
configuration.go Normal file
View File

@ -0,0 +1,13 @@
package srpc
import (
"log"
)
type LogErrorFunc func(format string, args ...interface{})
var logError = LogErrorFunc(log.Printf)
func SetLogError(f LogErrorFunc) {
logError = f
}

View File

@ -74,15 +74,20 @@ func (tc *NetConn) Send(payload interface{}) (err error) {
var header RPCHeader
var hb, b bytes.Buffer
if _, ok := payload.(*RPCHeartbeat); ok {
switch payload.(type) {
case *RPCHeartbeat:
header.RPCType = RPC_HEARTBEAT
} else if _, ok := payload.(*RPCClose); ok {
break
case *RPCClose:
header.RPCType = RPC_CLOSE
} else if _, ok := payload.(*RPCRequest); ok {
break
case *RPCRequest:
header.RPCType = RPC_REQUEST
} else if _, ok := payload.(*RPCResponse); ok {
break
case *RPCResponse:
header.RPCType = RPC_RESPONSE
} else {
break
default:
return errors.New("srpc - Invalid RPC message type")
}

View File

@ -4,6 +4,7 @@ import (
"bytes"
"errors"
"fmt"
"io"
"net"
"olznet.de/slog"
"reflect"
@ -235,3 +236,40 @@ func NewDefaultServer() *Server {
}
var DefaultServer = NewDefaultServer()
type IListener interface {
Init(addr string) error
Accept() (conn io.ReadWriteCloser, clientAddr string, err error)
Close() error
Addr() net.Addr
}
type netListener struct {
F func(addr string) (net.Listener, error)
L net.Listener
}
func (nl *netListener) Init(addr string) (err error) {
nl.L, err = nl.F(addr)
return err
}
func (nl *netListener) Accept() (conn io.ReadWriteCloser, clientAddr string, err error) {
var c net.Conn
if c, err = nl.L.Accept(); err != nil {
return nil, "", err
}
return c, c.RemoteAddr().String(), nil
}
func (nl *netListener) Close() error {
return nl.L.Close()
}
func (nl *netListener) Addr() net.Addr {
if nl.L == nil {
return nil
}
return nl.L.Addr()
}