HTTP JSONRPC Access from Web Page
Question:
Is it possible to establish an HTTP JSONRPC connection to a server using only standard library tools?
Introduction:
The net/rpc and net/rpc/jsonrpc packages provide mechanisms for inter-process communication. This article explores the possibility of connecting to an HTTP JSONRPC server using the standard library, without the need for custom implementations.
Detailed Explanation:
An HTTP JSONRPC server setup involves creating an rpc.Server and registering a service object. The server then handles HTTP requests using rpc.DefaultRPCPath and rpc.DefaultDebugPath. However, the standard library implementation expects HTTP clients to initiate a CONNECT request and write JSON RPC data directly to the stream. This approach may not be practical from browsers or simple command-line tools like CURL.
Solution:
Despite the apparent limitation, it is possible to create an HTTP JSONRPC server that can receive POST requests. This can be achieved by implementing a custom HTTP handler that adapts the HTTP request/response to a ServerCodec.
The handler defines a HttpConn struct that wraps the HTTP request body and response writer as a ReadWriteCloser, which is required by the ServerCodec.
Test Code Example:
The provided test code demonstrates how to create an HTTP JSONRPC server and make a POST request to it. A simple CakeBaker service is defined and registered on the server.
The HTTP handler serves requests at /bake-me-a-cake and uses a Jsonrpc.NewServerCodec to convert the HTTP request to a ServerCodec.
A POST request is made to the server with a JSON payload containing the method call and parameters. The server responds with a JSON response containing the method output.
Conclusion:
The standard library can be used to create an HTTP JSONRPC server that can receive POST requests. By implementing a custom HTTP handler, the limitation of direct CONNECT requests is bypassed, allowing for easy integration with web pages and command-line tools.
The above is the detailed content of Can Standard Library Tools Create an HTTP JSON-RPC Connection from a Web Page?. For more information, please follow other related articles on the PHP Chinese website!