Home > Backend Development > Golang > How to Make JSON-RPC Requests from a Web Page Using Go\'s net/rpc Package?

How to Make JSON-RPC Requests from a Web Page Using Go\'s net/rpc Package?

Patricia Arquette
Release: 2024-11-25 14:46:14
Original
626 people have browsed it

How to Make JSON-RPC Requests from a Web Page Using Go's net/rpc Package?

Making JSON-RPC Requests from a Web Page

The net/rpc and net/rpc/jsonrpc packages in Go provide a way to communicate between Go processes using JSON-RPC. However, connecting to a JSON-RPC server from a web page using only the standard library is not directly supported. While the server is expecting an HTTP client to issue a CONNECT request, web browsers and command-line tools like cURL typically use POST requests.

Custom HTTP Adapter

To address this, you can create a custom HTTP adapter to handle the conversion between HTTP requests and responses and a ServerCodec, which is used by the JSON-RPC server.

Code Example

Here's an example of a custom HTTP adapter and a test service:

import (
    "bytes"
    "fmt"
    "io"
    "io/ioutil"
    "log"
    "net"
    "net/http"
    "net/rpc"
    "net/rpc/jsonrpc"
    "testing"
)

// adapt HTTP connection to ReadWriteCloser
type HttpConn struct {
    in  io.Reader
    out io.Writer
}

func (c *HttpConn) Read(p []byte) (n int, err error)  { return c.in.Read(p) }
func (c *HttpConn) Write(d []byte) (n int, err error) { return c.out.Write(d) }
func (c *HttpConn) Close() error                      { return nil }

// our service
type CakeBaker struct{}

func (cb *CakeBaker) BakeIt(n int, msg *string) error {
    *msg = fmt.Sprintf("your cake has been bacon (%d)", n)
    return nil
}

func TestHTTPServer(t *testing.T) {

    fmt.Printf("TestHTTPServer\n")

    cb := &CakeBaker{}

    server := rpc.NewServer()
    server.Register(cb)

    listener, e := net.Listen("tcp", ":4321")
    if e != nil {
        log.Fatal("listen error:", e)
    }
    defer listener.Close()

    go http.Serve(listener, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

        if r.URL.Path == "/bake-me-a-cake" {
            serverCodec := jsonrpc.NewServerCodec(&HttpConn{in: r.Body, out: w})
            w.Header().Set("Content-type", "application/json")
            w.WriteHeader(200)
            err := server.ServeRequest(serverCodec)
            if err != nil {
                log.Printf("Error while serving JSON request: %v", err)
                http.Error(w, "Error while serving JSON request, details have been logged.", 500)
                return
            }
        }

    }))

    resp, err := http.Post("http://localhost:4321/bake-me-a-cake", "application/json", bytes.NewBufferString(
        `{"jsonrpc":"2.0","id":1,"method":"CakeBaker.BakeIt","params":[10]}`,
    ))
    if err != nil {
        panic(err)
    }

    defer resp.Body.Close()

    b, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }

    fmt.Printf("returned JSON: %s\n", string(b))
}
Copy after login

By using this adapter, you can create a JSON-RPC server that accepts POST requests and processes them using the standard JSON-RPC protocol.

The above is the detailed content of How to Make JSON-RPC Requests from a Web Page Using Go\'s net/rpc Package?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template