go-gun/gun/peer.go

62 lines
1.4 KiB
Go
Raw Normal View History

2019-02-20 20:54:46 +00:00
package gun
import (
"context"
2019-02-22 06:46:19 +00:00
"fmt"
2019-02-20 20:54:46 +00:00
"net/url"
"github.com/gorilla/websocket"
)
2019-02-22 09:23:14 +00:00
type ErrPeer struct {
Err error
Peer Peer
}
func (e *ErrPeer) Error() string { return fmt.Sprintf("Error on peer %v: %v", e.Peer, e.Err) }
2019-02-20 20:54:46 +00:00
type Peer interface {
2019-02-22 06:46:19 +00:00
Send(ctx context.Context, msg *Message) error
Receive() <-chan *MessageOrError
2019-02-20 20:54:46 +00:00
Close() error
}
2019-02-22 06:46:19 +00:00
type MessageOrError struct {
Message *Message
Err error
}
2019-02-20 20:54:46 +00:00
var PeerURLSchemes = map[string]func(context.Context, *url.URL) (Peer, error){
"ws": func(ctx context.Context, peerUrl *url.URL) (Peer, error) { return NewPeerWebSocket(ctx, peerUrl) },
}
2019-02-22 06:46:19 +00:00
func NewPeer(ctx context.Context, peerURL string) (Peer, error) {
if parsedURL, err := url.Parse(peerURL); err != nil {
return nil, err
} else if peerNew := PeerURLSchemes[parsedURL.Scheme]; peerNew == nil {
return nil, fmt.Errorf("Unknown peer URL scheme %v", parsedURL.Scheme)
} else {
return peerNew(ctx, parsedURL)
}
}
2019-02-20 20:54:46 +00:00
type PeerWebSocket struct {
*websocket.Conn
}
func NewPeerWebSocket(ctx context.Context, peerUrl *url.URL) (*PeerWebSocket, error) {
conn, _, err := websocket.DefaultDialer.DialContext(ctx, peerUrl.String(), nil)
if err != nil {
return nil, err
}
return &PeerWebSocket{conn}, nil
}
2019-02-22 06:46:19 +00:00
func (p *PeerWebSocket) Send(ctx context.Context, msg *Message) error {
panic("TODO")
}
func (p *PeerWebSocket) Receive() <-chan *MessageOrError {
panic("TODO")
}