- 支持 JSON-RPC 2.0 协议
- HTTP 和 TCP 客户端/服务端实现
- 自定义异常处理
- 并发安全
使用go get
命令安装:
go get github.com/lyonnee/jsonrpc2.0
import (
"log"
jsonrpc "github.com/lyonnee/jsonrpc2.0"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.POST("/", jsonrpc.GinHandler)
log.Fatal(r.Run(":8080"))
}
import (
"fmt"
"log"
jsonrpc "github.com/lyonnee/jsonrpc2.0"
)
func main() {
client, err := jsonrpc.NewHttpClient("http://localhost:8080")
if err != nil {
log.Fatalf("Error creating HTTP client: %v", err)
}
req := &jsonrpc.Request{
ID: 1,
Method: "exampleMethod",
JSONRPC: "2.0",
}
resp, err := client.Call(req)
if err != nil {
log.Fatalf("Error calling method: %v", err)
}
fmt.Printf("Response: %+v\n", resp)
}
import (
"fmt"
"log"
"net"
jsonrpc "github.com/lyonnee/jsonrpc2.0"
)
func main() {
conn, err := net.Dial("tcp", "localhost:8080")
if err != nil {
log.Fatalf("Error connecting to server: %v", err)
}
client, err := jsonrpc.NewTcpClient(conn)
if err != nil {
log.Fatalf("Error creating TCP client: %v", err)
}
req := &jsonrpc.Request{
ID: 1,
Method: "exampleMethod",
JSONRPC: "2.0",
}
resp, err := client.Call(req)
if err != nil {
log.Fatalf("Error calling method: %v", err)
}
fmt.Printf("Response: %+v\n", resp)
}
import (
"log"
"net"
jsonrpc "github.com/lyonnee/jsonrpc2.0"
)
func main() {
listener, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatalf("Error starting TCP server: %v", err)
}
defer listener.Close()
log.Println("Server is listening on port 8080")
for {
conn, err := listener.Accept()
if err != nil {
log.Println("Error accepting connection:", err)
continue
}
go jsonrpc.TcpHandler(conn)
}
}
可以设置自定义的异常处理函数:
jsonrpc.SetRecoverHandler(func(err any) {
fmt.Printf("Recovered from error: %v\n", err)
})
欢迎提交问题和拉取请求来改进jsonrpc2.0
。
jsonrpc2.0
遵循MIT许可证。查看LICENSE文件以获取更多信息。