You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

go-ethereum/rpc注册的方法调用失败,提示不存在问题求助

问题原因及解决方法

你遇到的问题是因为注册的方法签名不符合go-ethereum RPC框架的要求,导致方法没有被成功注册到服务中。

go-ethereum的rpc包对服务方法有两个核心要求:

  • 方法必须是导出方法(首字母大写,这点你已经满足)
  • 方法必须返回至少两个值,且最后一个返回值必须是error类型

你的Add方法仅返回单个int值,没有返回error,所以rpc服务器会忽略这个方法,不会将其加入到可调用的方法列表中,因此调用时提示方法不存在。

修改后的代码

package main

import (
    "log"
    "net/http"

    "github.com/ethereum/go-ethereum/rpc"
)

type ExampleService struct{}

// 调整方法签名,增加error返回值(即使不需要返回错误,也要返回nil)
func (e *ExampleService) Add(a, b int) (int, error) {
    return a + b, nil
}

func main() {
    server := rpc.NewServer()
    server.RegisterName("example", new(ExampleService))
    http.Handle("/", server)
    log.Fatal(http.ListenAndServe(":8545", nil))
}

验证调用

重新运行服务后,执行以下curl命令:

$ curl -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"example.Add","params":[3,4],"id":1}' http://localhost:8545

此时会得到正确的响应:

{"jsonrpc":"2.0","id":1,"result":7}

内容的提问来源于stack exchange,提问作者Rodrigo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 19:03:31