wsrpc

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2023 License: BSD-3-Clause Imports: 8 Imported by: 0

README

wsrpc

a tiny websocket rpc library.

Install

go get github.com/weiwenchen2022/wsrpc

Uasage

define service
type Args struct {
	A, B int
}

type Quotient struct {
	Quo, Rem int
}

type Arith int

func (*Arith) Multiply(args *Args, reply *int) error {
	*reply = args.A * args.B
	return nil
}

func (*Arith) Divide(args *Args, quo *Quotient) error {
	if args.B == 0 {
		return errors.New("divide by zero")
	}
	quo.Quo = args.A / args.B
	quo.Rem = args.A % args.B
	return nil
}
start a server
s := wsrpc.NewServer("")
s.Register(new(Arith))
http.ListenAndServe(":3000", s)
start a client
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cl, err := wsrpc.Dial(ctx, "http://localhost:3000","")
if err != nil {
	log.Fatal("dialing:", err)
}
defer cl.Close()

// Synchronous call
args := &server.Args{7,8}
var reply int
err = client.Call("Arith.Multiply", args, &reply)
if err != nil {
	log.Fatal("arith error:", err)
}
fmt.Printf("Arith: %d * %d = %d", args.A, args.B, reply)

// Asynchronous call
quotient := new(Quotient)
divCall := client.Go("Arith.Divide", args, quotient, nil)
<-divCall.Done	// will be equal to divCall
// check errors, print, etc.

Reference

GoDoc: https://pkg.go.dev/github.com/weiwenchen2022/wsrpc

Documentation

Overview

wsrpc is a minimal and idiomatic WebSocket rpc library for Go.

Index

Constants

View Source
const DefaultWsRPCPath = "/_wsRPC_"

Variables

This section is empty.

Functions

func Dial

func Dial(ctx context.Context, addr, rpcPath string) (*rpc.Client, error)

Dial connects to an websocket RPC server at the specified address and path. If rpcPath is empty use DefaultWsRPCPath.

Types

type Server

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

func NewServer

func NewServer(rpcPath string) *Server

NewServer returns a new Server at the specified rpc path. If rpcPath is empty use DefaultWsRPCPath.

func (*Server) Register

func (s *Server) Register(rcvr any) error

func (*Server) RegisterName

func (s *Server) RegisterName(name string, rcvr any) error

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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