jsonrpc 服务器接受请求的小写方法名称(用于大写注册服务)

Posted

技术标签:

【中文标题】jsonrpc 服务器接受请求的小写方法名称(用于大写注册服务)【英文标题】:jsonrpc server to accept requested lowercase method names (intended for uppercase registered services) 【发布时间】:2019-01-14 10:28:43 【问题描述】:

我正在尝试编写一个 jsonrpc 服务器,它将接受请求的小写方法名称,例如 Arith.multiply,并正确地将它们路由到相应的大写方法,例如 Arith.Multiply。这可能吗?

附:它是用于测试的生产服务器的轻量级克隆,API 是固定的,包括小写的方法名称,所以我不能将请求的方法名称更改为大写。

package main

import (
    "log"
    "net/http"

    "github.com/gorilla/mux"
    "github.com/gorilla/rpc"
    "github.com/gorilla/rpc/json"
)

type Args struct 
    A, B int


type Arith int

type Result int

func (t *Arith) Multiply(r *http.Request, args *Args, result *Result) error 
    log.Printf("Multiplying %d with %d\n", args.A, args.B)
    *result = Result(args.A * args.B)
    return nil


func main() 
    s := rpc.NewServer()
    s.RegisterCodec(json.NewCodec(), "application/json")
    s.RegisterCodec(json.NewCodec(), "application/json;charset=UTF-8")
    arith := new(Arith)
    s.RegisterService(arith, "")

    r := mux.NewRouter()
    r.Handle("/rpc", s)
    http.ListenAndServe(":1234", r)


【问题讨论】:

我怀疑你可以。 【参考方案1】:

看来您可以将一些东西偷偷带入自定义编解码器,以将小写方法定向到正确的大写方法。编写 gorilla/rpc/json 实现的 CodecRequest,您可以继续使用所有 gorilla 机器来处理请求。

下面的工作示例。看起来很长,但都是cmets。

package main

import (
    "fmt"
    "log"
    "net/http"
    "strings"
    "unicode"
    "unicode/utf8"

    "github.com/gorilla/mux"
    "github.com/gorilla/rpc"
    "github.com/gorilla/rpc/json"
)

type Args struct 
    A, B int

type Arith int

type Result int

func (t *Arith) Multiply(r *http.Request, args *Args, result *Result) error 
    log.Printf("Multiplying %d with %d\n", args.A, args.B)
    *result = Result(args.A * args.B)
    return nil


// UpCodec creates a CodecRequest to process each request.
type UpCodec struct 


// NewUpCodec returns a new UpCodec.
func NewUpCodec() *UpCodec 
    return &UpCodec


// NewRequest returns a new CodecRequest of type UpCodecRequest.
func (c *UpCodec) NewRequest(r *http.Request) rpc.CodecRequest 
    outerCR := &UpCodecRequest   // Our custom CR
    jsonC := json.NewCodec()       // json Codec to create json CR
    innerCR := jsonC.NewRequest(r) // create the json CR, sort of.

    // NOTE - innerCR is of the interface type rpc.CodecRequest.
    // Because innerCR is of the rpc.CR interface type, we need a
    // type assertion in order to assign it to our struct field's type.
    // We defined the source of the interface implementation here, so
    // we can be confident that innerCR will be of the correct underlying type
    outerCR.CodecRequest = innerCR.(*json.CodecRequest)
    return outerCR


// UpCodecRequest decodes and encodes a single request. UpCodecRequest
// implements gorilla/rpc.CodecRequest interface primarily by embedding
// the CodecRequest from gorilla/rpc/json. By selectively adding
// CodecRequest methods to UpCodecRequest, we can modify that behaviour
// while maintaining all the other remaining CodecRequest methods from
// gorilla's rpc/json implementation
type UpCodecRequest struct 
    *json.CodecRequest


// Method returns the decoded method as a string of the form "Service.Method"
// after checking for, and correcting a lowercase method name
// By being of lower depth in the struct , Method will replace the implementation
// of Method() on the embedded CodecRequest. Because the request data is part
// of the embedded json.CodecRequest, and unexported, we have to get the
// requested method name via the embedded CR's own method Method().
// Essentially, this just intercepts the return value from the embedded
// gorilla/rpc/json.CodecRequest.Method(), checks/modifies it, and passes it
// on to the calling rpc server.
func (c *UpCodecRequest) Method() (string, error) 
    m, err := c.CodecRequest.Method()
    if len(m) > 1 && err == nil 
        parts := strings.Split(m, ".")
        service, method := parts[0], parts[1]
        r, n := utf8.DecodeRuneInString(method) // get the first rune, and it's length
        if unicode.IsLower(r) 
            upMethod := service + "." + string(unicode.ToUpper(r)) + method[n:]
            log.Printf("lowercase method %s requested: treated as %s\n", m, upMethod)
            return upMethod, err
        
    
    return m, err


func main() 
    s := rpc.NewServer()

    // Register our own Codec
    s.RegisterCodec(NewUpCodec(), "application/json")
    s.RegisterCodec(NewUpCodec(), "application/json;charset=UTF-8")

    arith := new(Arith)
    s.RegisterService(arith, "")
    r := mux.NewRouter()
    r.Handle("/rpc", s)
    fmt.Println(http.ListenAndServe(":1234", r))

通过以下方式调用方法:

curl -X POST -H "Content-Type: application/json" -d '"id": 1, "method": "Arith.multiply", "params": ["A": 10, "B": 30]' 127.0.0.1:1234/rpc

【讨论】:

它不起作用或我做错了:pastebin.com/qKkGTuNw curl -X POST -H "Content-Type: application/json" -d '"id": 1, "method": "Arith .multiply", "params": ["A": 10, "B": 30]' 127.0.0.1:1234/rpc rpc: 找不到方法 "Arith.multiply" 您必须使用导出(大写)方法进行 rpc 调用。 rpc 包无法访问未导出(小写)的方法。 我知道,但是需要复制api合约。 api合约是小写方式吗? 是的,小写:(

以上是关于jsonrpc 服务器接受请求的小写方法名称(用于大写注册服务)的主要内容,如果未能解决你的问题,请参考以下文章

哪个简单的基于 python 的 WSGI 兼容 jsonrpc 库在服务器端用于“睡衣”?

向 JSON RPC 回调函数添加参数

接受任意类型的回调

JSONRpc Client over websocket C#

python中的JsonRpc客户端

带有 curl 的 JSONRPC 请求