Go中HTTP上的JSONRPC
如何基于in-Go在HTTP上使用JSON-RPC Go在Go中HTTP上的JSONRPC,http,go,json-rpc,Http,Go,Json Rpc,如何基于in-Go在HTTP上使用JSON-RPC Go在net/RPC/jsonrpc中提供JSON-RPC编解码器,但此编解码器使用网络连接作为输入,因此您无法将其与Go RPC HTTP处理程序一起使用。我附上了将TCP用于JSON-RPC的示例代码: func main() { cal := new(Calculator) server := rpc.NewServer() server.Register(cal) listener, e := net.L
net/RPC/jsonrpc
中提供JSON-RPC编解码器,但此编解码器使用网络连接作为输入,因此您无法将其与Go RPC HTTP处理程序一起使用。我附上了将TCP用于JSON-RPC的示例代码:
func main() {
cal := new(Calculator)
server := rpc.NewServer()
server.Register(cal)
listener, e := net.Listen("tcp", ":1234")
if e != nil {
log.Fatal("listen error:", e)
}
for {
if conn, err := listener.Accept(); err != nil {
log.Fatal("accept error: " + err.Error())
} else {
log.Printf("new connection established\n")
go server.ServeCodec(jsonrpc.NewServerCodec(conn))
}
}
}
内置RPC HTTP处理程序在被劫持的HTTP连接上使用gob编解码器。下面是如何对JSONRPC执行同样的操作 编写一个HTTP处理程序,使用被劫持的连接运行JSONRPC服务器
func serveJSONRPC(w http.ResponseWriter, req *http.Request) {
if req.Method != "CONNECT" {
http.Error(w, "method must be connect", 405)
return
}
conn, _, err := w.(http.Hijacker).Hijack()
if err != nil {
http.Error(w, "internal server error", 500)
return
}
defer conn.Close()
io.WriteString(conn, "HTTP/1.0 Connected\r\n\r\n")
jsonrpc.ServeConn(conn)
}
向HTTP服务器注册此处理程序。例如:
http.HandleFunc("/rpcendpoint", serveJSONRPC)
编辑:OP已经更新了问题,以明确他们想要GET/POST而不是connect。什么是“rpc http处理程序”?@CeriseLimon函数在默认http服务器中注册http处理程序。提到您必须使用GET或POST作为HTTP方法,但我认为这在您的方式中是不正确的。@ParhamAlvani您的问题和对问题的评论指向此解决方案。更新问题,说出你想要的。谢谢,我已经更新了我的问题。但我认为这个解决方案是基于Go内置库的最佳解决方案。