Go 中的net/rpc 和net/rpc/jsonrpc 套件提供了一種使用JSON 在Go 進程之間進行通訊的方法-RPC。但是,不直接支援僅使用標準庫從網頁連接到 JSON-RPC 伺服器。雖然伺服器期望 HTTP 用戶端發出 CONNECT 請求,但 Web 瀏覽器和 cURL 等命令列工具通常使用 POST 請求。
要解決此問題,您可以建立自訂HTTP 適配器
程式碼範例
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)) }
以上是如何使用 Go 的 net/rpc 套件從網頁發出 JSON-RPC 請求?的詳細內容。更多資訊請關注PHP中文網其他相關文章!