栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从网页访问golang http + jsonrpc

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从网页访问golang http + jsonrpc

FWIW,我通过制作一个简单的HTTP处理程序使HTTP请求/响应适应ServerCodec来完成此工作。看起来像是一种魅力。

这是工作代码作为测试:

import (    "bytes"    "fmt"    "io"    "io/ioutil"    "log"    "net"    "net/http"    "net/rpc"    "net/rpc/jsonrpc"    "testing")// adapt HTTP connection to ReadWriteClosertype 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 servicetype 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("TestHTTPServern")    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: %sn", string(b))}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/448002.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号