refactor: 重构,修复包引用问题;添加rtu相关连接封装

main
NoahLan 1 year ago
parent ebcbd0f88f
commit e99030b919

@ -4,10 +4,10 @@ import (
"errors" "errors"
"fmt" "fmt"
"git.noahlan.cn/noahlan/nnet/packet" "git.noahlan.cn/noahlan/nnet/packet"
"git.noahlan.cn/noahlan/nnet/serialize"
"git.noahlan.cn/noahlan/nnet/session" "git.noahlan.cn/noahlan/nnet/session"
"git.noahlan.cn/noahlan/ntools-go/core/nlog" "git.noahlan.cn/noahlan/ntool/ndef"
"git.noahlan.cn/noahlan/ntools-go/core/pool" "git.noahlan.cn/noahlan/ntool/nlog"
"github.com/panjf2000/ants/v2"
"net" "net"
"sync/atomic" "sync/atomic"
) )
@ -42,13 +42,14 @@ type (
Connection struct { Connection struct {
conf Config // 配置 conf Config // 配置
session *session.Session // Session session *session.Session // Session
pool *ants.Pool // 连接池
status int32 // 连接状态 status int32 // 连接状态
conn net.Conn // low-level conn fd conn net.Conn // low-level conn fd
typ ConnType // 连接类型 typ ConnType // 连接类型
packer packet.Packer // 封包、拆包器 packer packet.Packer // 封包、拆包器
serializer serialize.Serializer // 消息序列化/反序列化器 serializer ndef.Serializer // 消息序列化/反序列化器
pipeline Pipeline // 连接生命周期管理 pipeline Pipeline // 连接生命周期管理
handleFn func(conn *Connection, pkg packet.IPacket) // 消息处理方法 handleFn func(conn *Connection, pkg packet.IPacket) // 消息处理方法
@ -75,14 +76,16 @@ type (
func NewConnection( func NewConnection(
id int64, id int64,
conn net.Conn, conn net.Conn,
pool *ants.Pool,
conf Config, conf Config,
packerBuilder packet.PackerBuilder, packerBuilder packet.PackerBuilder,
serializer serialize.Serializer, serializer ndef.Serializer,
pipeline Pipeline, pipeline Pipeline,
handleFn packetFn) *Connection { handleFn packetFn) *Connection {
r := &Connection{ r := &Connection{
conf: conf, conf: conf,
session: session.NewSession(id), session: session.NewSession(id),
pool: pool,
status: StatusStart, status: StatusStart,
conn: conn, conn: conn,
@ -158,11 +161,11 @@ func (r *Connection) SetLastMID(mid uint64) {
} }
func (r *Connection) Serve() { func (r *Connection) Serve() {
_ = pool.Submit(func() { _ = r.pool.Submit(func() {
r.write() r.write()
}) })
_ = pool.Submit(func() { _ = r.pool.Submit(func() {
r.read() r.read()
}) })
} }
@ -278,7 +281,7 @@ func (r *Connection) processPacket(packet packet.IPacket) error {
if r.Status() == StatusWorking { if r.Status() == StatusWorking {
// 处理包消息 // 处理包消息
_ = pool.Submit(func() { _ = r.pool.Submit(func() {
r.handleFn(r, packet) r.handleFn(r, packet)
}) })
} }

@ -2,7 +2,7 @@ package connection
import ( import (
"errors" "errors"
"git.noahlan.cn/noahlan/ntools-go/core/nlog" "git.noahlan.cn/noahlan/ntool/nlog"
"sync" "sync"
"sync/atomic" "sync/atomic"
) )

@ -0,0 +1,39 @@
package connection
import (
"github.com/goburrow/serial"
"net"
"time"
)
// RTUConn rtu connection wrapper
type RTUConn struct {
serial.Port
config *serial.Config
}
// NewRTUConn 新建 RTUConn
func NewRTUConn(port serial.Port, cfg *serial.Config) net.Conn {
return &RTUConn{Port: port, config: cfg}
}
func (c *RTUConn) LocalAddr() net.Addr {
cfg := c.config
return NewRTUAddr(cfg.Address, cfg.BaudRate, cfg.DataBits, cfg.StopBits, cfg.Parity)
}
func (c *RTUConn) RemoteAddr() net.Addr {
return c.LocalAddr()
}
func (c *RTUConn) SetDeadline(_ time.Time) error {
return nil
}
func (c *RTUConn) SetReadDeadline(_ time.Time) error {
return nil
}
func (c *RTUConn) SetWriteDeadline(_ time.Time) error {
return nil
}

@ -0,0 +1,35 @@
package connection
import (
"fmt"
"net"
)
const RTUNetwork = "rtu"
type RTUAddr struct {
Address string
BaudRate int
DataBits int
StopBits int
Parity string
}
func NewRTUAddr(addr string, rate int, dataBits int, stopBits int, parity string) net.Addr {
return &RTUAddr{
Address: addr,
BaudRate: rate,
DataBits: dataBits,
StopBits: stopBits,
Parity: parity,
}
}
func (r *RTUAddr) Network() string {
return RTUNetwork
}
// String form of address (for example, "/dev/ttyS0|19200|8|1|N", "com1|19200|8|1|N")
func (r *RTUAddr) String() string {
return fmt.Sprintf("%s|%d|%d|%d", r.Address, r.BaudRate, r.DataBits, r.StopBits)
}

@ -9,7 +9,7 @@ import (
"git.noahlan.cn/noahlan/nnet/scheduler" "git.noahlan.cn/noahlan/nnet/scheduler"
"git.noahlan.cn/noahlan/nnet/serialize" "git.noahlan.cn/noahlan/nnet/serialize"
"git.noahlan.cn/noahlan/nnet/session" "git.noahlan.cn/noahlan/nnet/session"
"git.noahlan.cn/noahlan/ntools-go/core/nlog" "git.noahlan.cn/noahlan/ntool/nlog"
"github.com/panjf2000/ants/v2" "github.com/panjf2000/ants/v2"
"math" "math"
"net" "net"
@ -109,6 +109,7 @@ func (ngin *Engine) handle(conn net.Conn) *connection.Connection {
nc := connection.NewConnection( nc := connection.NewConnection(
ngin.sessIdMgr.SessionID(), ngin.sessIdMgr.SessionID(),
conn, conn,
ngin.goPool,
connection.Config{LogDebug: ngin.ShallLogDebug(), LogPrefix: ngin.LogPrefix()}, connection.Config{LogDebug: ngin.ShallLogDebug(), LogPrefix: ngin.LogPrefix()},
ngin.packerBuilder, ngin.serializer, ngin.pipeline, ngin.packerBuilder, ngin.serializer, ngin.pipeline,
ngin.router.Handle, ngin.router.Handle,

@ -4,20 +4,21 @@ go 1.20
require ( require (
github.com/gorilla/websocket v1.5.0 github.com/gorilla/websocket v1.5.0
github.com/panjf2000/ants/v2 v2.7.3 // indirect github.com/panjf2000/ants/v2 v2.7.5 // indirect
) )
require google.golang.org/protobuf v1.28.2-0.20220831092852-f930b1dc76e8 require google.golang.org/protobuf v1.28.2-0.20220831092852-f930b1dc76e8
require ( require (
git.noahlan.cn/noahlan/ntools-go/core v1.1.3 git.noahlan.cn/noahlan/ntool v1.0.1 // indirect
github.com/fatih/color v1.15.0 // indirect github.com/fatih/color v1.15.0 // indirect
github.com/goburrow/serial v0.1.0 // indirect
github.com/gofrs/uuid/v5 v5.0.0 // indirect github.com/gofrs/uuid/v5 v5.0.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.17 // indirect github.com/mattn/go-isatty v0.0.19 // indirect
go.opentelemetry.io/otel v1.14.0 // indirect go.opentelemetry.io/otel v1.16.0 // indirect
go.opentelemetry.io/otel/trace v1.14.0 // indirect go.opentelemetry.io/otel/trace v1.16.0 // indirect
golang.org/x/crypto v0.7.0 // indirect golang.org/x/crypto v0.10.0 // indirect
golang.org/x/sys v0.6.0 // indirect golang.org/x/sys v0.9.0 // indirect
golang.org/x/text v0.8.0 // indirect golang.org/x/text v0.10.0 // indirect
) )

@ -1,3 +1,5 @@
git.noahlan.cn/noahlan/ntool v1.0.1 h1:c2sw65BmyqQHKn3+s2Bjdkz9AtSKI4e1WAkRi/CG1oc=
git.noahlan.cn/noahlan/ntool v1.0.1/go.mod h1:nLp9j4lz203kNpVFrNbT25A2QHbx235gXv+Ut1bX8E8=
git.noahlan.cn/noahlan/ntools-go/core v1.1.3 h1:n4z0KaXmX/fmobavxCMc2vGJDoStbhNbm8AZugPEPGg= git.noahlan.cn/noahlan/ntools-go/core v1.1.3 h1:n4z0KaXmX/fmobavxCMc2vGJDoStbhNbm8AZugPEPGg=
git.noahlan.cn/noahlan/ntools-go/core v1.1.3/go.mod h1:pmwee9V76Cyp6nVr3dPj5TpePLvRpc8C0ZgAzFIFAKU= git.noahlan.cn/noahlan/ntools-go/core v1.1.3/go.mod h1:pmwee9V76Cyp6nVr3dPj5TpePLvRpc8C0ZgAzFIFAKU=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@ -7,6 +9,8 @@ github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs=
github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw=
github.com/go-logr/logr v1.2.3 h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0= github.com/go-logr/logr v1.2.3 h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/goburrow/serial v0.1.0 h1:v2T1SQa/dlUqQiYIT8+Cu7YolfqAi3K96UmhwYyuSrA=
github.com/goburrow/serial v0.1.0/go.mod h1:sAiqG0nRVswsm1C97xsttiYCzSLBmUZ/VSlVLZJ8haA=
github.com/gofrs/uuid/v5 v5.0.0 h1:p544++a97kEL+svbcFbCQVM9KFu0Yo25UoISXGNNH9M= github.com/gofrs/uuid/v5 v5.0.0 h1:p544++a97kEL+svbcFbCQVM9KFu0Yo25UoISXGNNH9M=
github.com/gofrs/uuid/v5 v5.0.0/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV+9bD8= github.com/gofrs/uuid/v5 v5.0.0/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV+9bD8=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
@ -19,8 +23,10 @@ github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovk
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng= github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng=
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/panjf2000/ants/v2 v2.7.3 h1:rHQ0hH0DQvuNUqqlWIMJtkMcDuL1uQAfpX2mIhQ5/s0= github.com/panjf2000/ants/v2 v2.7.3 h1:rHQ0hH0DQvuNUqqlWIMJtkMcDuL1uQAfpX2mIhQ5/s0=
github.com/panjf2000/ants/v2 v2.7.3/go.mod h1:KIBmYG9QQX5U2qzFP/yQJaq/nSb6rahS9iEHkrCMgM8= github.com/panjf2000/ants/v2 v2.7.3/go.mod h1:KIBmYG9QQX5U2qzFP/yQJaq/nSb6rahS9iEHkrCMgM8=
github.com/panjf2000/ants/v2 v2.7.5/go.mod h1:KIBmYG9QQX5U2qzFP/yQJaq/nSb6rahS9iEHkrCMgM8=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
@ -32,18 +38,23 @@ github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o
github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
go.opentelemetry.io/otel v1.14.0 h1:/79Huy8wbf5DnIPhemGB+zEPVwnN6fuQybr/SRXa6hM= go.opentelemetry.io/otel v1.14.0 h1:/79Huy8wbf5DnIPhemGB+zEPVwnN6fuQybr/SRXa6hM=
go.opentelemetry.io/otel v1.14.0/go.mod h1:o4buv+dJzx8rohcUeRmWUZhqupFvzWis188WlggnNeU= go.opentelemetry.io/otel v1.14.0/go.mod h1:o4buv+dJzx8rohcUeRmWUZhqupFvzWis188WlggnNeU=
go.opentelemetry.io/otel v1.16.0/go.mod h1:vl0h9NUa1D5s1nv3A5vZOYWn8av4K8Ml6JDeHrT/bx4=
go.opentelemetry.io/otel/sdk v1.14.0 h1:PDCppFRDq8A1jL9v6KMI6dYesaq+DFcDZvjsoGvxGzY= go.opentelemetry.io/otel/sdk v1.14.0 h1:PDCppFRDq8A1jL9v6KMI6dYesaq+DFcDZvjsoGvxGzY=
go.opentelemetry.io/otel/trace v1.14.0 h1:wp2Mmvj41tDsyAJXiWDWpfNsOiIyd38fy85pyKcFq/M= go.opentelemetry.io/otel/trace v1.14.0 h1:wp2Mmvj41tDsyAJXiWDWpfNsOiIyd38fy85pyKcFq/M=
go.opentelemetry.io/otel/trace v1.14.0/go.mod h1:8avnQLK+CG77yNLUae4ea2JDQ6iT+gozhnZjy/rw9G8= go.opentelemetry.io/otel/trace v1.14.0/go.mod h1:8avnQLK+CG77yNLUae4ea2JDQ6iT+gozhnZjy/rw9G8=
go.opentelemetry.io/otel/trace v1.16.0/go.mod h1:Yt9vYq1SdNz3xdjZZK7wcXv1qv2pwLkqr2QVwea0ef0=
golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A= golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A=
golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU=
golang.org/x/crypto v0.10.0/go.mod h1:o4eNf7Ede1fv+hwOwZsTHl9EsPFO6q6ZvYR8vYfY45I=
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o= golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68=
golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.10.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.28.2-0.20220831092852-f930b1dc76e8 h1:KR8+MyP7/qOlV+8Af01LtjL04bu7on42eVsxT4EyBQk= google.golang.org/protobuf v1.28.2-0.20220831092852-f930b1dc76e8 h1:KR8+MyP7/qOlV+8Af01LtjL04bu7on42eVsxT4EyBQk=

@ -5,7 +5,7 @@ import (
"git.noahlan.cn/noahlan/nnet/connection" "git.noahlan.cn/noahlan/nnet/connection"
"git.noahlan.cn/noahlan/nnet/packet" "git.noahlan.cn/noahlan/nnet/packet"
rt "git.noahlan.cn/noahlan/nnet/router" rt "git.noahlan.cn/noahlan/nnet/router"
"git.noahlan.cn/noahlan/ntools-go/core/nlog" "git.noahlan.cn/noahlan/ntool/nlog"
"sync/atomic" "sync/atomic"
"time" "time"
) )

@ -5,6 +5,8 @@ import "errors"
var ( var (
// ErrWrongPacketType represents a wrong packet type. // ErrWrongPacketType represents a wrong packet type.
ErrWrongPacketType = errors.New("wrong packet type") ErrWrongPacketType = errors.New("wrong packet type")
// ErrPacketSizeExceed represents a wrong packet size.
ErrPacketSizeExceed = errors.New("packet size exceed")
) )
type ( type (

@ -1,43 +0,0 @@
package modbus
import "sync"
var crcTable []uint16
var mu sync.Mutex
// crcModbus 计算modbus的crc
func crcModbus(data []byte) (crc uint16) {
if crcTable == nil {
mu.Lock()
if crcTable == nil {
initCrcTable()
}
mu.Unlock()
}
crc = 0xffff
for _, v := range data {
crc = (crc >> 8) ^ crcTable[(crc^uint16(v))&0x00FF]
}
return crc
}
// initCrcTable 初始化crcTable
func initCrcTable() {
crc16IBM := uint16(0xA001)
crcTable = make([]uint16, 256)
for i := uint16(0); i < 256; i++ {
crc := uint16(0)
c := i
for j := uint16(0); j < 8; j++ {
if ((crc ^ c) & 0x0001) > 0 {
crc = (crc >> 1) ^ crc16IBM
} else {
crc = crc >> 1
}
c = c >> 1
}
crcTable[i] = crc
}
}

@ -1,14 +0,0 @@
package modbus
import (
"git.noahlan.cn/noahlan/nnet/protocol/modbus/internal"
"testing"
)
func TestCRC(t *testing.T) {
got := crcModbus([]byte{0x01, 0x04, 0x02, 0xFF, 0xFF})
expect := uint16(0x80B8)
assert := internal.NewAssert(t, "TestCRC")
assert.Equal(expect, got)
}

@ -1,167 +0,0 @@
package internal
import (
"fmt"
"reflect"
"runtime"
"testing"
)
const (
compareNotEqual int = iota - 2
compareLess
compareEqual
compareGreater
)
// Assert is a simple implementation of assertion, only for internal usage
type Assert struct {
T *testing.T
CaseName string
}
// NewAssert return instance of Assert
func NewAssert(t *testing.T, caseName string) *Assert {
return &Assert{T: t, CaseName: caseName}
}
// Equal check if expected is equal with actual
func (a *Assert) Equal(expected, actual any) {
if compare(expected, actual) != compareEqual {
makeTestFailed(a.T, a.CaseName, expected, actual)
}
}
// NotEqual check if expected is not equal with actual
func (a *Assert) NotEqual(expected, actual any) {
if compare(expected, actual) == compareEqual {
expectedInfo := fmt.Sprintf("not %v", expected)
makeTestFailed(a.T, a.CaseName, expectedInfo, actual)
}
}
// Greater check if expected is greate than actual
func (a *Assert) Greater(expected, actual any) {
if compare(expected, actual) != compareGreater {
expectedInfo := fmt.Sprintf("> %v", expected)
makeTestFailed(a.T, a.CaseName, expectedInfo, actual)
}
}
// GreaterOrEqual check if expected is greate than or equal with actual
func (a *Assert) GreaterOrEqual(expected, actual any) {
isGreatOrEqual := compare(expected, actual) == compareGreater || compare(expected, actual) == compareEqual
if !isGreatOrEqual {
expectedInfo := fmt.Sprintf(">= %v", expected)
makeTestFailed(a.T, a.CaseName, expectedInfo, actual)
}
}
// Less check if expected is less than actual
func (a *Assert) Less(expected, actual any) {
if compare(expected, actual) != compareLess {
expectedInfo := fmt.Sprintf("< %v", expected)
makeTestFailed(a.T, a.CaseName, expectedInfo, actual)
}
}
// LessOrEqual check if expected is less than or equal with actual
func (a *Assert) LessOrEqual(expected, actual any) {
isLessOrEqual := compare(expected, actual) == compareLess || compare(expected, actual) == compareEqual
if !isLessOrEqual {
expectedInfo := fmt.Sprintf("<= %v", expected)
makeTestFailed(a.T, a.CaseName, expectedInfo, actual)
}
}
// IsNil check if value is nil
func (a *Assert) IsNil(value any) {
if value != nil {
makeTestFailed(a.T, a.CaseName, nil, value)
}
}
// IsNotNil check if value is not nil
func (a *Assert) IsNotNil(value any) {
if value == nil {
makeTestFailed(a.T, a.CaseName, "not nil", value)
}
}
// compare x and y return :
// x > y -> 1, x < y -> -1, x == y -> 0, x != y -> -2
func compare(x, y any) int {
vx := reflect.ValueOf(x)
vy := reflect.ValueOf(y)
if vx.Type() != vy.Type() {
return compareNotEqual
}
switch vx.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
xInt := vx.Int()
yInt := vy.Int()
if xInt > yInt {
return compareGreater
}
if xInt == yInt {
return compareEqual
}
if xInt < yInt {
return compareLess
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
xUint := vx.Uint()
yUint := vy.Uint()
if xUint > yUint {
return compareGreater
}
if xUint == yUint {
return compareEqual
}
if xUint < yUint {
return compareLess
}
case reflect.Float32, reflect.Float64:
xFloat := vx.Float()
yFloat := vy.Float()
if xFloat > yFloat {
return compareGreater
}
if xFloat == yFloat {
return compareEqual
}
if xFloat < yFloat {
return compareLess
}
case reflect.String:
xString := vx.String()
yString := vy.String()
if xString > yString {
return compareGreater
}
if xString == yString {
return compareEqual
}
if xString < yString {
return compareLess
}
default:
if reflect.DeepEqual(x, y) {
return compareEqual
}
return compareNotEqual
}
return compareNotEqual
}
// logFailedInfo make test failed and log error info
func makeTestFailed(t *testing.T, caseName string, expected, actual any) {
_, file, line, _ := runtime.Caller(2)
errInfo := fmt.Sprintf("Case %v failed. file: %v, line: %v, expected: %v, actual: %v.", caseName, file, line, expected, actual)
t.Error(errInfo)
t.FailNow()
}

@ -1,50 +0,0 @@
package internal
import (
"testing"
)
func TestAssert(t *testing.T) {
assert := NewAssert(t, "TestAssert")
assert.Equal(0, 0)
assert.NotEqual(1, 0)
assert.NotEqual("1", 1)
var uInt1 uint
var uInt2 uint
var uInt8 uint8
var uInt16 uint16
var uInt32 uint32
var uInt64 uint64
assert.NotEqual(uInt1, uInt8)
assert.NotEqual(uInt8, uInt16)
assert.NotEqual(uInt16, uInt32)
assert.NotEqual(uInt32, uInt64)
assert.Equal(uInt1, uInt2)
uInt1 = 1
uInt2 = 2
assert.Less(uInt1, uInt2)
assert.Greater(1, 0)
assert.GreaterOrEqual(1, 1)
assert.Less(0, 1)
assert.LessOrEqual(0, 0)
assert.Equal(0.1, 0.1)
assert.Greater(1.1, 0.1)
assert.Less(0.1, 1.1)
assert.Equal("abc", "abc")
assert.NotEqual("abc", "abd")
assert.Less("abc", "abd")
assert.Greater("abd", "abc")
assert.Equal([]int{1, 2, 3}, []int{1, 2, 3})
assert.NotEqual([]int{1, 2, 3}, []int{1, 2})
assert.IsNil(nil)
assert.IsNotNil("abc")
}

@ -7,7 +7,7 @@ import (
"git.noahlan.cn/noahlan/nnet" "git.noahlan.cn/noahlan/nnet"
"git.noahlan.cn/noahlan/nnet/connection" "git.noahlan.cn/noahlan/nnet/connection"
"git.noahlan.cn/noahlan/nnet/packet" "git.noahlan.cn/noahlan/nnet/packet"
"git.noahlan.cn/noahlan/ntools-go/core/nlog" "git.noahlan.cn/noahlan/ntool/nlog"
) )
type OnReadyFunc func() type OnReadyFunc func()

@ -5,7 +5,7 @@ import (
"git.noahlan.cn/noahlan/nnet/connection" "git.noahlan.cn/noahlan/nnet/connection"
"git.noahlan.cn/noahlan/nnet/middleware" "git.noahlan.cn/noahlan/nnet/middleware"
"git.noahlan.cn/noahlan/nnet/packet" "git.noahlan.cn/noahlan/nnet/packet"
"git.noahlan.cn/noahlan/ntools-go/core/nlog" "git.noahlan.cn/noahlan/ntool/nlog"
"time" "time"
) )

@ -7,7 +7,7 @@ import (
"git.noahlan.cn/noahlan/nnet" "git.noahlan.cn/noahlan/nnet"
"git.noahlan.cn/noahlan/nnet/connection" "git.noahlan.cn/noahlan/nnet/connection"
"git.noahlan.cn/noahlan/nnet/packet" "git.noahlan.cn/noahlan/nnet/packet"
"git.noahlan.cn/noahlan/ntools-go/core/nlog" "git.noahlan.cn/noahlan/ntool/nlog"
) )
type ( type (

@ -6,7 +6,7 @@ import (
"git.noahlan.cn/noahlan/nnet/connection" "git.noahlan.cn/noahlan/nnet/connection"
"git.noahlan.cn/noahlan/nnet/packet" "git.noahlan.cn/noahlan/nnet/packet"
rt "git.noahlan.cn/noahlan/nnet/router" rt "git.noahlan.cn/noahlan/nnet/router"
"git.noahlan.cn/noahlan/ntools-go/core/nlog" "git.noahlan.cn/noahlan/ntool/nlog"
) )
type ( type (

@ -4,7 +4,7 @@ import (
"git.noahlan.cn/noahlan/nnet/connection" "git.noahlan.cn/noahlan/nnet/connection"
"git.noahlan.cn/noahlan/nnet/packet" "git.noahlan.cn/noahlan/nnet/packet"
"git.noahlan.cn/noahlan/nnet/router" "git.noahlan.cn/noahlan/nnet/router"
"git.noahlan.cn/noahlan/ntools-go/core/nlog" "git.noahlan.cn/noahlan/ntool/nlog"
) )
type Router struct { type Router struct {

@ -3,7 +3,7 @@ package router
import ( import (
"git.noahlan.cn/noahlan/nnet/connection" "git.noahlan.cn/noahlan/nnet/connection"
"git.noahlan.cn/noahlan/nnet/packet" "git.noahlan.cn/noahlan/nnet/packet"
"git.noahlan.cn/noahlan/ntools-go/core/nlog" "git.noahlan.cn/noahlan/ntool/nlog"
) )
type ( type (

@ -1,7 +1,7 @@
package scheduler package scheduler
import ( import (
"git.noahlan.cn/noahlan/ntools-go/core/nlog" "git.noahlan.cn/noahlan/ntool/nlog"
"runtime/debug" "runtime/debug"
"sync/atomic" "sync/atomic"
"time" "time"

@ -1,7 +1,7 @@
package scheduler package scheduler
import ( import (
"git.noahlan.cn/noahlan/ntools-go/core/nlog" "git.noahlan.cn/noahlan/ntool/nlog"
"math" "math"
"runtime/debug" "runtime/debug"
"sync" "sync"

@ -2,12 +2,12 @@ package json
import ( import (
"encoding/json" "encoding/json"
"git.noahlan.cn/noahlan/nnet/serialize" "git.noahlan.cn/noahlan/ntool/ndef"
) )
type Serializer struct{} type Serializer struct{}
func NewSerializer() serialize.Serializer { func NewSerializer() ndef.Serializer {
return &Serializer{} return &Serializer{}
} }

@ -2,7 +2,7 @@ package protobuf
import ( import (
"errors" "errors"
"git.noahlan.cn/noahlan/nnet/serialize" "git.noahlan.cn/noahlan/ntool/ndef"
"google.golang.org/protobuf/proto" "google.golang.org/protobuf/proto"
) )
@ -11,7 +11,7 @@ var ErrWrongValueType = errors.New("protobuf: convert on wrong type value")
type Serializer struct{} type Serializer struct{}
func NewSerializer() serialize.Serializer { func NewSerializer() ndef.Serializer {
return &Serializer{} return &Serializer{}
} }

@ -1,19 +0,0 @@
package serialize
type (
// Marshaler 序列化
Marshaler interface {
Marshal(v interface{}) ([]byte, error)
}
// Unmarshaler 反序列化
Unmarshaler interface {
Unmarshal(data []byte, v interface{}) error
}
// Serializer 消息 序列化/反序列化仅针对payload
Serializer interface {
Marshaler
Unmarshaler
}
)

@ -8,15 +8,15 @@ import (
"git.noahlan.cn/noahlan/nnet/packet" "git.noahlan.cn/noahlan/nnet/packet"
protocol_nnet "git.noahlan.cn/noahlan/nnet/protocol/nnet" protocol_nnet "git.noahlan.cn/noahlan/nnet/protocol/nnet"
rt "git.noahlan.cn/noahlan/nnet/router" rt "git.noahlan.cn/noahlan/nnet/router"
"git.noahlan.cn/noahlan/ntools-go/core/nlog" "git.noahlan.cn/noahlan/ntool/nlog"
"git.noahlan.cn/noahlan/ntools-go/core/pool" "git.noahlan.cn/noahlan/ntool/npool"
"math" "math"
"time" "time"
) )
func runServer(addr string) { func runServer(addr string) {
nginOpts := make([]nnet.RunOption, 0) nginOpts := make([]nnet.RunOption, 0)
nginOpts = append(nginOpts, nnet.WithPoolCfg(pool.Config{ nginOpts = append(nginOpts, nnet.WithPoolCfg(npool.Config{
PoolSize: math.MaxInt32, PoolSize: math.MaxInt32,
ExpiryDuration: time.Second, ExpiryDuration: time.Second,
PreAlloc: false, PreAlloc: false,
@ -68,7 +68,7 @@ func runClient(addr string) (*nnet.Engine, *connection.Connection) {
chReady := make(chan struct{}) chReady := make(chan struct{})
nginOpts := make([]nnet.RunOption, 0) nginOpts := make([]nnet.RunOption, 0)
nginOpts = append(nginOpts, nnet.WithPoolCfg(pool.Config{ nginOpts = append(nginOpts, nnet.WithPoolCfg(npool.Config{
PoolSize: math.MaxInt32, PoolSize: math.MaxInt32,
ExpiryDuration: time.Second, ExpiryDuration: time.Second,
PreAlloc: false, PreAlloc: false,

Loading…
Cancel
Save