owtp

package
v2.4.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 14, 2022 License: GPL-3.0 Imports: 31 Imported by: 3

README

OWTP Protocal

OWTP协议全称OpenWallet Transfer Protocol,是一种基于点对点的分布式通信协议。 OWTP协议能够让开发者专注于解决应用业务实现,无需关心底层的网络连接实现。 通过简单的配置就能够让两端建立不同的网络连接方式,路由可复用,业务无需重写。

框架特点

  • 支持多种网络连接协议:http,websocket,mq等。
  • 支持多种网络传输数据格式:目前只有JSON,未来支持Protobuf。
  • 内置SM2协商密码机制,无需https,也可实现加密通信。
  • 内置数字签名,防重放,防中途篡改数据。
  • 支持多种session缓存方案。
  • 多种网络连接协议复用统一的路由配置。

如何使用

创建节点

    //1. 使用配置文件创建
    cert, err := NewCertificate(RandomPrivateKey())
    if err != nil {
        return nil
    }
    
    config := NodeConfig{
        Cert: cert,    //配置节点证书
        TimeoutSEC: 60 //请求超时时间
    }
    
    host := NewNode(config)
    
    //2. 随机创建一个带证书的节点
    host := RandomOWTPNode()
	
可选配置Session

    //创建一个全局的会话管理器,详细资料参考sesssion包的README.md
    globalSessions, _ = owtp.NewSessionManager("memory", &session.ManagerConfig{
		Gclifetime: 10,
	})
	go globalSessions.GC()
	
	//设置节点Peerstore指向一个全局的会话管理
	host.SetPeerstore(globalSessions)

节点作为服务端使用

    //外置的业务方法
     func getInfo (ctx *Context) {
        //记录当前连接的信息到session,用于上下文操作
        ctx.SetSession("username", "kkk")
    
        ctx.Resp = Response{
            Status: 0,
            Msg:    "success",
            Result: map[string]interface{}{
                "getInfo": "hi boy",
            },
        }
    }
    
    
    //配置路由的业务方法
    host.HandleFunc("getInfo", getInfo)

    //配置处理业务前的准备过程【可选】
	host.HandlePrepareFunc(func(ctx *Context) {
		
	})

    //配置处理业务后的结束过程【可选】
	host.HandleFinishFunc(func(ctx *Context) {
		
		//断开节点连接,长连接才响应,HTTP为短连接,不会响应
        host.ClosePeer(peer.ID)
	})

	//开启端口监听HTTP连接请求
	host.Listen(
		ConnectConfig{
			Address:     ":9432",
			ConnectType: HTTP,
			EnableSignature: true, //开启数字签名
		})

	//开启端口监听websocket连接请求
	host.Listen(
		ConnectConfig{
			Address:     ":9433",
			ConnectType: Websocket,
		})
    
    //更多复杂的连接配置可查看ConnectConfig类

    //监听长连接打开,处理后续业务(HTTP为短连接,不支持)
	host.SetOpenHandler(func(n *OWTPNode, peer PeerInfo) {
		log.Infof("peer[%s] connected", peer.ID)
		log.Infof("peer[%+v] config", peer.Config)
	})

    //监听长连接断开,处理后续业务(HTTP为短连接,不支持)
	wsHost.SetCloseHandler(func(n *OWTPNode, peer PeerInfo) {
		
	})

节点作为客户端使用

    //随机创建带证书的客户端
    client := RandomOWTPNode()
    
    //配置路由的业务方法
    client.HandleFunc("getInfo", getInfo)
    
    //通过HTTP连接服务端
    err := client.Connect("testhost", ConnectConfig{
        Address:     ":9432",
        ConnectType: HTTP,
        EnableSignature: true, //开启数字签名
    })
    
    /*
    //或通过Websocket连接服务端
    err := client.Connect("testhost", ConnectConfig{
            Address:     ":9433",
            ConnectType: Websocket,
        })
    */

    if err != nil {
        return
    }

    //向已连接的testhost主机,开启协商密码,加密方式AES
    err = client.KeyAgreement("testhost", "aes")
    if err != nil {
        return
    }

    params := map[string]interface{}{
        "name": "chance",
        "age":  18,
    }

    //向已连接的testhost主机,发起业务请求
    //参数1:主机ID,参数2:路由的方法名,参数3:业务参数,参数4:是否同步线程,参数5:响应结果处理
    //参数4 sync = true,程序会等待响应结果处理完,才走程序下一步处理。
    err = client.Call("testhost", "getInfo", params, true, func(resp Response) {

        result := resp.JsonData()
        symbols := result.Get("getInfo")
        fmt.Printf("getInfo: %v\n", symbols)
    })

    if err != nil {
        return
    }
	

Documentation

Overview

owtp全称OpenWallet Transfer Protocol,OpenWallet的一种点对点的分布式私有通信协议。

owtp全称OpenWallet Transfer Protocol,OpenWallet的一种点对点的分布式私有通信协议。

Index

Constants

View Source
const (
	XForwardedFor = "X-Forwarded-For"
	XRealIP       = "X-Real-IP"
)
View Source
const (
	WSRequest  = 1 //请求标识
	WSResponse = 2 //响应标识
)
View Source
const (

	//成功标识
	StatusSuccess uint64 = 200

	//客户端请求错误
	ErrBadRequest uint64 = 400
	//网络断开
	ErrUnauthorized uint64 = 401
	//通信密钥不正确
	ErrSecretKeyInvalid uint64 = 402
	//找不到方法
	ErrNotFoundMethod uint64 = 404
	//重放攻击
	ErrReplayAttack uint64 = 409
	//请求超时
	ErrRequestTimeout uint64 = 408
	//网络断开
	ErrNetworkDisconnected uint64 = 430
	//服务器错误
	ErrInternalServerError uint64 = 500
	//请求与响应的方法不一致
	ErrResponseMethodDiffer uint64 = 501
	//协商失败
	ErrKeyAgreementFailed uint64 = 502
	//拒绝服务
	ErrDenialOfService uint64 = 503

	//60X: 自定义错误
	ErrCustomError uint64 = 600
)
View Source
const (
	Websocket string = "ws"
	MQ        string = "mq"
	HTTP      string = "http"
)

连接方式

View Source
const (

	//校验协商结果
	KeyAgreementMethod = "internal_keyAgreement"

	//准备前执行的方
	PrepareMethod = "internal_prepare"

	//结束时执行的方法
	FinishMethod = "internal_finish"
)

内置方法

View Source
const (
	DataPacketVersionV1 = 1 //数据包版本v1

	CurrentDataPacketVersion = DataPacketVersionV1 //当前的数据包版本
)
View Source
const (
	WriteWait      = 60 * time.Second
	PongWait       = 30 * time.Second
	PingPeriod     = (PongWait * 9) / 10
	MaxMessageSize = 1 * 1024
)

局部常量

View Source
const (
	DefaultTimoutSEC = 60
)

Variables

View Source
var (
	Debug = false
)

Functions

func ClientIP

func ClientIP(req *http.Request) string

func GenerateRangeNum

func GenerateRangeNum(min, max int) int

GenerateRangeNum 生成范围内的随机整数

func HttpError added in v2.0.8

func HttpError(w http.ResponseWriter, r *http.Request, error string, code int)

HttpError 错误

func HttpListenAddr

func HttpListenAddr(addr string, enableSignature bool, handler PeerHandler) (*httpListener, error)

ListenAddr 创建OWTP协议通信监听

func JsonUnmarshal added in v2.4.3

func JsonUnmarshal(data []byte, v interface{}) error

JsonUnmarshal json decode

func NewOWTPPeerstore

func NewOWTPPeerstore() *owtpPeerstore

NewPeerstore 创建支持OWTP协议的Peerstore

func RandomPrivateKey

func RandomPrivateKey() string

RandomPrivateKey 生成随机私钥

func WSListenAddr

func WSListenAddr(addr string, cert Certificate, enableSignature bool, handler PeerHandler) (*wsListener, error)

WSListenAddr 创建websocket通信监听

Types

type Authorization

type Authorization interface {

	//EnableAuth 开启授权
	EnableAuth() bool

	//GenerateSignature 生成签名,并把签名加入到DataPacket中
	GenerateSignature(data *DataPacket) bool
	//VerifySignature 校验签名,若验证错误,可更新错误信息到DataPacket中
	VerifySignature(data *DataPacket) bool

	//EnableKeyAgreement 开启密码协商
	EnableKeyAgreement() bool
	//InitKeyAgreement 发起协商
	InitKeyAgreement(keyAgreement *KeyAgreement) error
	//RequestKeyAgreement 请求协商,计算密钥
	RequestKeyAgreement(keyAgreement *KeyAgreement) error
	//ResponseKeyAgreement 响应协商,计算密钥
	ResponseKeyAgreement(keyAgreement *KeyAgreement) error
	//VerifyKeyAgreement 验证协商结果
	VerifyKeyAgreement(keyAgreement *KeyAgreement) bool

	//EncryptData 加密数据
	EncryptData(data []byte, key []byte) ([]byte, error)
	//DecryptData 解密数据
	DecryptData(data []byte, key []byte) ([]byte, error)
	//EncryptDataPacket 加密数据
	EncryptDataPacket(data *DataPacket, key []byte) error
	//DecryptDataPacket 解密数据
	DecryptDataPacket(data *DataPacket, key []byte) error
}

Authorization 授权

type AuthorizationBase

type AuthorizationBase struct{}

func (*AuthorizationBase) DecryptData

func (base *AuthorizationBase) DecryptData(data []byte, key []byte) ([]byte, error)

DecryptData 解密数据

func (*AuthorizationBase) DecryptDataPacket

func (base *AuthorizationBase) DecryptDataPacket(data *DataPacket, key []byte) error

DecryptDataPacket 解密数据

func (*AuthorizationBase) EnableAuth

func (base *AuthorizationBase) EnableAuth() bool

EnableAuth 开启授权

func (*AuthorizationBase) EnableKeyAgreement

func (base *AuthorizationBase) EnableKeyAgreement() bool

EnableKeyAgreement 开启密码协商

func (*AuthorizationBase) EncryptData

func (base *AuthorizationBase) EncryptData(data []byte, key []byte) ([]byte, error)

EncryptData 加密数据

func (*AuthorizationBase) EncryptDataPacket

func (base *AuthorizationBase) EncryptDataPacket(data *DataPacket, key []byte) error

EncryptDataPacket 加密数据

func (*AuthorizationBase) GenerateSignature

func (base *AuthorizationBase) GenerateSignature(data *DataPacket) bool

GenerateSignature 生成签名,并把签名加入到DataPacket中

func (*AuthorizationBase) InitKeyAgreement

func (base *AuthorizationBase) InitKeyAgreement(keyAgreement *KeyAgreement) error

InitKeyAgreement 发起协商

func (*AuthorizationBase) RequestKeyAgreement

func (base *AuthorizationBase) RequestKeyAgreement(keyAgreement *KeyAgreement) error

RequestKeyAgreement 请求协商,计算密钥

func (*AuthorizationBase) ResponseKeyAgreement

func (base *AuthorizationBase) ResponseKeyAgreement(keyAgreement *KeyAgreement) error

ResponseKeyAgreement 响应协商,计算密钥

func (*AuthorizationBase) VerifyKeyAgreement

func (base *AuthorizationBase) VerifyKeyAgreement(keyAgreement *KeyAgreement) bool

VerifyKeyAgreement 是否完成密码协商,验证协商结果

func (*AuthorizationBase) VerifySignature

func (base *AuthorizationBase) VerifySignature(data *DataPacket) bool

VerifySignature 校验签名,若验证错误,可更新错误信息到DataPacket中

type Certificate

type Certificate struct {
	// contains filtered or unexported fields
}

func NewCertificate

func NewCertificate(privateKey string, consultType ...string) (Certificate, error)

func NewRandomCertificate

func NewRandomCertificate() Certificate

RandomPrivateKey 生成随机私钥

func (*Certificate) ID

func (cert *Certificate) ID() string

func (*Certificate) KeyPair

func (cert *Certificate) KeyPair() (priv string, pub string)

func (*Certificate) PrivateKeyBytes

func (cert *Certificate) PrivateKeyBytes() []byte

func (*Certificate) PublicKeyBytes

func (cert *Certificate) PublicKeyBytes() []byte

type ConnectConfig

type ConnectConfig struct {
	Address            string `json:"address"`            //@required 连接IP地址
	ConnectType        string `json:"connectType"`        //@required 连接方式
	EnableSignature    bool   `json:"enableSignature"`    //是否开启owtp协议内签名,防重放
	Account            string `json:"account"`            //mq账户名
	Password           string `json:"password"`           //mq账户密码
	Exchange           string `json:"exchange"`           //mq需要字段
	WriteQueueName     string `json:"writeQueueName"`     //mq写入通道名
	ReadQueueName      string `json:"readQueueName"`      //mq读取通道名
	EnableSSL          bool   `json:"enableSSL"`          //是否开启链接SSL,https,wss
	ReadBufferSize     int    `json:"readBufferSize"`     //socket读取缓存
	WriteBufferSize    int    `json:"writeBufferSize"`    //socket写入缓存
	EnableKeyAgreement bool   `json:"enableKeyAgreement"` //是否开启协商密码
}

节点主配置 作为json解析工具

type ConnectType

type ConnectType int

type Context

type Context struct {
	//节点ID
	PID string
	//传输类型,1:请求,2:响应
	Req uint64
	//请求的远程IP
	RemoteAddress string

	//方法
	Method string
	//响应
	Resp Response

	//节点指针
	Peer Peer
	//数据包版本
	Version int64
	// contains filtered or unexported fields
}

func NewContext

func NewContext(req, nonce uint64, pid, method string, inputs interface{}) *Context

NewContext

func (*Context) DelSession

func (ctx *Context) DelSession(name string)

DelSession removes value from session.

func (*Context) DestroySession

func (ctx *Context) DestroySession()

DestroySession cleans session data

func (*Context) GetSession

func (ctx *Context) GetSession(name string) interface{}

GetSession gets value from session.

func (*Context) Params

func (ctx *Context) Params() gjson.Result

Params 获取参数

func (*Context) Response

func (ctx *Context) Response(result interface{}, status uint64, msg string)

func (*Context) ResponseStopRun

func (ctx *Context) ResponseStopRun(result interface{}, status uint64, msg string)

ResponseStopRun 中断操作,Context.stop = true,将不再执行后面的绑定的业务 并完成Response处理

func (*Context) SetSession

func (ctx *Context) SetSession(name string, value interface{})

SetSession puts value into session.

type DataPacket

type DataPacket struct {
	Req        uint64      `json:"r"`
	Method     string      `json:"m"`
	Nonce      uint64      `json:"n" storm:"id"`
	Timestamp  int64       `json:"t"`
	Data       interface{} `json:"d"`
	Signature  string      `json:"s"`
	SecretData SecretData  `json:"k"`
	Version    int64       `json:"v"`
}

DataPacket 数据包

func NewDataPacket

func NewDataPacket(json gjson.Result) *DataPacket

NewDataPacket 通过 gjson转为DataPacket

type HTTPClient

type HTTPClient struct {
	ReadBufferSize  int
	WriteBufferSize int
	// contains filtered or unexported fields
}

HTTPClient 基于http的通信服务端

func HTTPDial

func HTTPDial(
	pid, url string,
	handler PeerHandler,
	header map[string]string,
	timeout time.Duration) (*HTTPClient, error)

func NewHTTPClient

func NewHTTPClient(pid string, responseWriter http.ResponseWriter, request *http.Request, hander PeerHandler, auth Authorization) (*HTTPClient, error)

func NewHTTPClientWithHeader

func NewHTTPClientWithHeader(responseWriter http.ResponseWriter, request *http.Request, hander PeerHandler, enableSignature bool) (*HTTPClient, error)

func (*HTTPClient) ConnectConfig

func (c *HTTPClient) ConnectConfig() ConnectConfig

func (*HTTPClient) EnableKeyAgreement

func (c *HTTPClient) EnableKeyAgreement() bool

func (*HTTPClient) HandleRequest

func (c *HTTPClient) HandleRequest() error

readRequest 读取请求

func (*HTTPClient) IsConnected

func (c *HTTPClient) IsConnected() bool

func (*HTTPClient) IsHost

func (c *HTTPClient) IsHost() bool

func (*HTTPClient) LocalAddr

func (c *HTTPClient) LocalAddr() net.Addr

LocalAddr 本地节点地址

func (*HTTPClient) PID

func (c *HTTPClient) PID() string

func (*HTTPClient) RemoteAddr

func (c *HTTPClient) RemoteAddr() net.Addr

RemoteAddr 远程节点地址

type HandlerFunc

type HandlerFunc func(ctx *Context)

路由处理方法

type KeyAgreement

type KeyAgreement struct {
	EncryptType            string //协商密码类型
	PublicKeyInitiator     string //发送方:本地公钥
	PrivateKeyInitiator    string //发送方:本地私钥
	TmpPublicKeyInitiator  string //发送方:临时公钥
	TmpPrivateKeyInitiator string //发送方:临时私钥
	PublicKeyResponder     string //响应方:本地公钥
	PrivateKeyResponder    string //响应方:本地私钥
	TmpPublicKeyResponder  string //响应方:临时公钥
	TmpPrivateKeyResponder string //响应方:临时私钥
	S2                     string //响应方:本地验证码,RequestKeyAgreement生成
	SB                     string //响应方:生成协商密码的必要验证码,RequestKeyAgreement生成
	SA                     string //发送方:本地验证码,ResponseKeyAgreement生成
	Key                    string //协商的密钥
}

KeyAgreement 协商密码

type Listener

type Listener interface {
	Accept() (Peer, error)
	Close() error
	Addr() net.Addr
}

Listener 监听接口定义

type MQClient

type MQClient struct {
	ReadBufferSize  int
	WriteBufferSize int
	// contains filtered or unexported fields
}

MQClient 基于mq的通信客户端

func MQDial

func MQDial(pid, url string, handler PeerHandler) (*MQClient, error)

Dial connects a client to the given URL.

func NewMQClient

func NewMQClient(pid string, conn *amqp.Connection, channel *amqp.Channel, hander PeerHandler, auth Authorization, done func()) (*MQClient, error)

func (*MQClient) ConnectConfig

func (c *MQClient) ConnectConfig() ConnectConfig

func (*MQClient) EnableKeyAgreement

func (c *MQClient) EnableKeyAgreement() bool

func (*MQClient) IsConnected

func (c *MQClient) IsConnected() bool

func (*MQClient) IsHost

func (c *MQClient) IsHost() bool

func (*MQClient) LocalAddr

func (c *MQClient) LocalAddr() net.Addr

LocalAddr 本地节点地址

func (*MQClient) PID

func (c *MQClient) PID() string

func (*MQClient) RemoteAddr

func (c *MQClient) RemoteAddr() net.Addr

RemoteAddr 远程节点地址

type MqAddr

type MqAddr struct {
	NetWork string
}

func (*MqAddr) Network

func (m *MqAddr) Network() string

func (*MqAddr) String

func (m *MqAddr) String() string

type NodeConfig

type NodeConfig struct {
	TimeoutSEC int         `json:"timeoutSEC"` //超时时间
	Cert       Certificate `json:"cert"`       //证书
	Peerstore  Peerstore   //会话缓存
}

节点主配置 作为json解析工具

type OWTPAuth

type OWTPAuth struct {
	AuthorizationBase
	// contains filtered or unexported fields
}

Authorization 授权

func NewOWTPAuthWithCertificate

func NewOWTPAuthWithCertificate(cert Certificate, enable bool) (*OWTPAuth, error)

func (*OWTPAuth) DecryptData

func (auth *OWTPAuth) DecryptData(data []byte, key []byte) ([]byte, error)

DecryptData 解密数据

func (*OWTPAuth) DecryptDataPacket

func (auth *OWTPAuth) DecryptDataPacket(packet *DataPacket, key []byte) error

DecryptDataPacket 解密数据

func (*OWTPAuth) EnableAuth

func (auth *OWTPAuth) EnableAuth() bool

EnableAuth 开启授权

func (*OWTPAuth) EnableKeyAgreement

func (auth *OWTPAuth) EnableKeyAgreement() bool

EnableKeyAgreement 开启密码协商

func (*OWTPAuth) EncryptData

func (auth *OWTPAuth) EncryptData(data []byte, key []byte) ([]byte, error)

EncryptData 加密数据

func (*OWTPAuth) EncryptDataPacket

func (auth *OWTPAuth) EncryptDataPacket(packet *DataPacket, key []byte) error

EncryptDataPacket 加密数据

func (*OWTPAuth) GenerateSignature

func (auth *OWTPAuth) GenerateSignature(data *DataPacket) bool

GenerateSignature 生成签名,并把签名加入到DataPacket中

func (*OWTPAuth) HTTPAuthHeader

func (auth *OWTPAuth) HTTPAuthHeader() map[string]string

AuthHeader 返回授权头

func (*OWTPAuth) InitKeyAgreement

func (auth *OWTPAuth) InitKeyAgreement(keyAgreement *KeyAgreement) error

InitKeyAgreement 发起协商

func (*OWTPAuth) LocalPID

func (auth *OWTPAuth) LocalPID() string

LocalPID 远程节点ID

func (*OWTPAuth) RemotePID

func (auth *OWTPAuth) RemotePID() string

RemotePID 远程节点ID

func (*OWTPAuth) RequestKeyAgreement

func (auth *OWTPAuth) RequestKeyAgreement(keyAgreement *KeyAgreement) error

RequestKeyAgreement 请求协商

func (*OWTPAuth) ResponseKeyAgreement

func (auth *OWTPAuth) ResponseKeyAgreement(keyAgreement *KeyAgreement) error

ResponseKeyAgreement 响应协商

func (*OWTPAuth) VerifyKeyAgreement

func (auth *OWTPAuth) VerifyKeyAgreement(keyAgreement *KeyAgreement) bool

func (*OWTPAuth) VerifySignature

func (auth *OWTPAuth) VerifySignature(data *DataPacket) bool

VerifySignature 校验签名,若验证错误,可更新错误信息到DataPacket中

type OWTPNode

type OWTPNode struct {

	//Broadcast   chan BroadcastMessage
	Join  chan Peer
	Leave chan Peer
	Stop  chan struct{}
	// contains filtered or unexported fields
}

OWTPNode 实现OWTP协议的节点

func NewNode

func NewNode(config NodeConfig) *OWTPNode

NewNode 创建OWTP协议节点

func NewOWTPNode

func NewOWTPNode(cert Certificate, readBufferSize, writeBufferSize int) *OWTPNode

NewOWTPNode 创建OWTP协议节点

func RandomOWTPNode

func RandomOWTPNode(consultType ...string) *OWTPNode

RandomOWTPNode 创建随机密钥节点

func (*OWTPNode) AddOnlinePeer

func (node *OWTPNode) AddOnlinePeer(peer Peer)

AddOnlinePeer 添加在线节点

func (*OWTPNode) Call

func (node *OWTPNode) Call(
	pid string,
	method string,
	params interface{},
	sync bool,
	reqFunc RequestFunc) error

Call 向对方节点进行调用

func (*OWTPNode) CallSync

func (node *OWTPNode) CallSync(
	pid string,
	method string,
	params interface{},
) (*Response, error)

CallSync 同步请求

func (*OWTPNode) Certificate

func (node *OWTPNode) Certificate() *Certificate

Certificate 节点证书

func (*OWTPNode) Close

func (node *OWTPNode) Close()

Close 关闭节点

func (*OWTPNode) CloseListener

func (node *OWTPNode) CloseListener(connectType string)

CloseListener 关闭监听

func (*OWTPNode) ClosePeer

func (node *OWTPNode) ClosePeer(pid string)

ClosePeer 断开连接节点

func (*OWTPNode) Connect

func (node *OWTPNode) Connect(pid string, config ConnectConfig) (Peer, error)

Connect 建立长连接

func (*OWTPNode) ConnectAndCall

func (node *OWTPNode) ConnectAndCall(
	pid string,
	config ConnectConfig,
	method string,
	params interface{},
	sync bool,
	reqFunc RequestFunc) error

ConnectAndCall 通过连接配置并直接请求,如果节点在线使用当前连接请求

func (*OWTPNode) GetOnlinePeer

func (node *OWTPNode) GetOnlinePeer(id string) Peer

GetOnlinePeer 获取当前在线的Peer

func (*OWTPNode) GetValueForPeer

func (node *OWTPNode) GetValueForPeer(peer Peer, key string) interface{}

func (*OWTPNode) HandleFinishFunc

func (node *OWTPNode) HandleFinishFunc(handler HandlerFunc)

HandleFinishFunc 绑定结束后的处理方法

func (*OWTPNode) HandleFunc

func (node *OWTPNode) HandleFunc(method string, handler HandlerFunc)

HandleFunc 绑定路由器方法

func (*OWTPNode) HandlePrepareFunc

func (node *OWTPNode) HandlePrepareFunc(handler HandlerFunc)

HandlePrepareFunc 绑定准备前的处理方法

func (*OWTPNode) IsConnectPeer

func (node *OWTPNode) IsConnectPeer(pid string) bool

IsConnectPeer 是否连接某个节点

func (*OWTPNode) KeyAgreement

func (node *OWTPNode) KeyAgreement(pid string, consultType string) error

KeyAgreement 发起协商请求 这是一个同步请求

func (*OWTPNode) Listen

func (node *OWTPNode) Listen(config ConnectConfig) error

Listen 监听TCP地址

func (*OWTPNode) Listening

func (node *OWTPNode) Listening(connectType string) bool

listening 是否监听中

func (*OWTPNode) NodeID

func (node *OWTPNode) NodeID() string

NodeID 节点的ID

func (*OWTPNode) OnPeerClose

func (node *OWTPNode) OnPeerClose(peer Peer, reason string)

OnPeerClose 节点关闭

func (*OWTPNode) OnPeerNewDataPacketReceived

func (node *OWTPNode) OnPeerNewDataPacketReceived(peer Peer, packet *DataPacket)

OnPeerNewDataPacketReceived 节点获取新数据包

func (*OWTPNode) OnPeerOpen

func (node *OWTPNode) OnPeerOpen(peer Peer)

OnPeerOpen 节点连接成功

func (*OWTPNode) OnlinePeers

func (node *OWTPNode) OnlinePeers() []Peer

Peers 节点列表

func (*OWTPNode) Peerstore

func (node *OWTPNode) Peerstore() Peerstore

Peerstore 节点存储器

func (*OWTPNode) PutValueForPeer

func (node *OWTPNode) PutValueForPeer(peer Peer, key string, val interface{}) error

func (*OWTPNode) RemoveOfflinePeer

func (node *OWTPNode) RemoveOfflinePeer(id string)

RemoveOfflinePeer 移除不在线的节点

func (*OWTPNode) Run

func (node *OWTPNode) Run() error

Run 运行,go Run运行一条线程

func (*OWTPNode) SetCloseHandler

func (node *OWTPNode) SetCloseHandler(h func(n *OWTPNode, peer PeerInfo))

SetCloseHandler 设置关闭连接时的回调

func (*OWTPNode) SetOpenHandler

func (node *OWTPNode) SetOpenHandler(h func(n *OWTPNode, peer PeerInfo))

SetOpenHandler 设置开启连接时的回调

func (*OWTPNode) SetPeerstore

func (node *OWTPNode) SetPeerstore(store Peerstore)

SetPeerstore 设置一个Peerstore指针

func (*OWTPNode) SetReloadPeerInfoHandler added in v2.1.0

func (node *OWTPNode) SetReloadPeerInfoHandler(h func(n *OWTPNode, peerID string) PeerInfo)

SetReloadPeerInfoHandler 设置重新加载节点信息回调

type Param

type Param struct {
	// contains filtered or unexported fields
}

type Peer

type Peer interface {
	PID() string                  //节点ID
	IsHost() bool                 //是否主机,我方主动连接的节点
	IsConnected() bool            //是否已经连接
	LocalAddr() net.Addr          //本地节点地址
	RemoteAddr() net.Addr         //远程节点地址
	ConnectConfig() ConnectConfig // 返回配置信息
	EnableKeyAgreement() bool     //EnableKeyAgreement 开启密码协商
	// contains filtered or unexported methods
}

Peer 节点

type PeerAttribute

type PeerAttribute map[string]interface{}

type PeerHandler

type PeerHandler interface {
	OnPeerOpen(peer Peer)                                      //节点连接成功
	OnPeerClose(peer Peer, reason string)                      //节点关闭
	OnPeerNewDataPacketReceived(peer Peer, packet *DataPacket) //节点获取新数据包
	GetValueForPeer(peer Peer, key string) interface{}
	PutValueForPeer(peer Peer, key string, val interface{}) error
}

PeerHandler 节点监听器

type PeerInfo

type PeerInfo struct {
	ID     string
	Config ConnectConfig
}

type Peerstore

type Peerstore interface {
	// SaveAddr 保存节点地址
	SavePeer(peer Peer)

	//PeerInfo 节点信息
	PeerInfo(id string) PeerInfo

	// Get 获取节点属性
	Get(id string, key string) interface{}

	// GetString
	GetString(id string, key string) string

	// Put 设置节点属性
	Put(id string, key string, val interface{}) error

	// Delete 设置节点属性
	Delete(id string, key string) error

	//Destroy 清空store数据
	Destroy(id string) error
}

Peerstore 节点存储器

type RequestFunc

type RequestFunc func(resp Response)

请求方法,回调响应结果

type RequestQueue

type RequestQueue map[uint64]requestEntry

请求队列

type Response

type Response struct {
	Status uint64      `json:"status"`
	Msg    string      `json:"msg"`
	Result interface{} `json:"result"`
}

func (*Response) JsonData

func (resp *Response) JsonData() gjson.Result

JsonData the result of Response encode gjson

type SecretData

type SecretData struct {
	PublicKeyInitiator    string `json:"pk"`  //发起方公钥
	TmpPublicKeyInitiator string `json:"tpk"` //发起方临时公钥
	EncryptType           string `json:"et"`  //加密类型
	PublicKeyResponder    string `json:"pko"` //响应方公钥
	TmpPublicKeyResponder string `json:"tpo"` //响应方临时公钥
	SB                    string `json:"sb"`  //响应方发送给发起方的校验值
	SA                    string `json:"sa"`  //发起方发送给响应方的校验值
	S2                    string `json:"s2"`  //响应方协商密码计算的校验值
}

KeyAgreement 协商密码

type ServeMux

type ServeMux struct {
	// contains filtered or unexported fields
}

ServeMux 多路复用服务

func NewServeMux

func NewServeMux(timeoutSEC int) *ServeMux

func (*ServeMux) AddRequest

func (mux *ServeMux) AddRequest(peer Peer, nonce uint64, time int64, method string, reqFunc RequestFunc, respChan chan Response, sync bool) error

AddRequest 添加请求到队列 @param nonce 递增不可重复 @param method API方法名 @param reqFunc 异步请求的回调函数 @param respChan 同步请求的响应通道 @param sync 是否同步

func (*ServeMux) HandleFunc

func (mux *ServeMux) HandleFunc(method string, handler HandlerFunc)

HandleFunc 路由处理器绑定 @param method API方法名 @param handler 处理方法入口

func (*ServeMux) RemoveRequest

func (mux *ServeMux) RemoveRequest(pid string, nonce uint64) error

RemoveRequest 移除请求

func (*ServeMux) ResetRequestQueue

func (mux *ServeMux) ResetRequestQueue(pid string)

ResetRequestQueue 重置请求队列

func (*ServeMux) ServeOWTP

func (mux *ServeMux) ServeOWTP(pid string, ctx *Context)

ServeOWTP OWTP协议消息监听方法

type SessionManager

type SessionManager struct {
	// contains filtered or unexported fields
}

SessionManager contains Provider and its configuration.

func NewSessionManager

func NewSessionManager(provideName string, cf *session.ManagerConfig) (*SessionManager, error)

NewManager Create new Manager with provider name and json config string. provider name: 1. cookie 2. file 3. memory 4. redis 5. mysql json config: 1. is https default false 2. hashfunc default sha1 3. hashkey default beegosessionkey 4. maxage default is none

func (*SessionManager) Delete

func (store *SessionManager) Delete(id string, key string) error

Delete

func (*SessionManager) Destroy

func (store *SessionManager) Destroy(id string) error

Destroy

func (*SessionManager) GC

func (store *SessionManager) GC()

GC Start session gc process. it can do gc in times after gc lifetime.

func (*SessionManager) Get

func (store *SessionManager) Get(id string, key string) interface{}

Get 获取节点属性

func (*SessionManager) GetActiveSession

func (store *SessionManager) GetActiveSession() int

GetActiveSession Get all active sessions count number.

func (*SessionManager) GetProvider

func (store *SessionManager) GetProvider() session.Provider

GetProvider return current manager's provider

func (*SessionManager) GetSessionStore

func (store *SessionManager) GetSessionStore(pid string) (sessions session.Store, err error)

GetSessionStore Get SessionStore by its id.

func (*SessionManager) GetString

func (store *SessionManager) GetString(id string, key string) string

GetString

func (*SessionManager) PeerInfo

func (store *SessionManager) PeerInfo(id string) PeerInfo

PeerInfo 节点信息

func (*SessionManager) Put

func (store *SessionManager) Put(id string, key string, val interface{}) error

Put 设置节点属性

func (*SessionManager) SavePeer

func (store *SessionManager) SavePeer(peer Peer)

SaveAddr 保存节点

func (*SessionManager) SessionDestroy

func (store *SessionManager) SessionDestroy(pid string)

SessionDestroy Destroy session by its id in http request cookie.

type WSClient

type WSClient struct {
	ReadBufferSize  int
	WriteBufferSize int
	// contains filtered or unexported fields
}

WSClient 基于websocket的通信客户端

func Dial

func Dial(
	pid, url string,
	handler PeerHandler,
	header map[string]string,
	ReadBufferSize, WriteBufferSize int) (*WSClient, error)

Dial connects a client to the given URL.

func NewWSClient

func NewWSClient(pid string, conn *websocket.Conn, handler PeerHandler, auth Authorization, done func()) (*WSClient, error)

func NewWSClientWithHeader

func NewWSClientWithHeader(header http.Header, cert Certificate, conn *websocket.Conn, handler PeerHandler, enableSignature bool, done func()) (*WSClient, error)

func (*WSClient) ConnectConfig

func (c *WSClient) ConnectConfig() ConnectConfig

func (*WSClient) EnableKeyAgreement

func (c *WSClient) EnableKeyAgreement() bool

func (*WSClient) IsConnected

func (c *WSClient) IsConnected() bool

func (*WSClient) IsHost

func (c *WSClient) IsHost() bool

func (*WSClient) LocalAddr

func (c *WSClient) LocalAddr() net.Addr

LocalAddr 本地节点地址

func (*WSClient) PID

func (c *WSClient) PID() string

func (*WSClient) RemoteAddr

func (c *WSClient) RemoteAddr() net.Addr

RemoteAddr 远程节点地址

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL