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

如何在JSON-RPC调用中传递基础认证信息?

在Go的net/rpc/jsonrpc中添加基础认证支持

标准的net/rpc/jsonrpc包本身并没有直接内置基础认证的处理逻辑,因为它默认是基于原始TCP连接设计的。不过根据你的API使用的是HTTP还是自定义TCP协议的JSON-RPC,我们可以用不同的方式来实现认证:

情况1:API基于HTTP提供JSON-RPC服务(最常见)

如果你的JSON-RPC服务是通过HTTP暴露的,基础认证是HTTP协议层面的机制,我们需要先构造带有Authorization头的HTTP请求,再将请求的连接交给jsonrpc客户端:

import (
	"encoding/base64"
	"net/http"
	"net/rpc/jsonrpc"
)

func main() {
	// 替换为你的认证凭据
	username := "your-username"
	password := "your-password"

	// 生成基础认证的Base64编码字符串
	authStr := base64.StdEncoding.EncodeToString([]byte(username + ":" + password))

	// 创建指向JSON-RPC端点的POST请求
	req, err := http.NewRequest("POST", "http://localhost:1234/rpc", nil)
	if err != nil {
		// 这里建议换成实际的错误处理逻辑,比如返回错误或日志
		panic(err)
	}

	// 设置认证头和Content-Type
	req.Header.Set("Authorization", "Basic "+authStr)
	req.Header.Set("Content-Type", "application/json")

	// 发送请求并获取响应
	httpClient := &http.Client{}
	resp, err := httpClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	// 基于响应体创建jsonrpc客户端
	jsonClient := jsonrpc.NewClient(resp.Body)
	defer jsonClient.Close()

	// 执行RPC调用(替换为你的实际方法和参数)
	var reply string
	someArgs := "your-arguments"
	err = jsonClient.Call("someMethod", someArgs, &reply)
	if err != nil {
		panic(err)
	}

	// 使用返回的结果
	println(reply)
}

情况2:API基于自定义TCP协议的JSON-RPC

如果你的服务是直接基于TCP的自定义JSON-RPC协议,要求在发送RPC请求前先完成认证,那我们可以在建立TCP连接后,先向服务器发送认证数据,再创建jsonrpc客户端:

import (
	"encoding/json"
	"net"
	"net/rpc/jsonrpc"
)

// 根据服务器要求定义认证请求的结构
type AuthRequest struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

// 根据服务器响应定义认证结果结构
type AuthResponse struct {
	Success bool   `json:"success"`
	Msg     string `json:"msg,omitempty"`
}

func main() {
	// 建立TCP连接
	netClient, err := net.Dial("tcp", "localhost:1234")
	if err != nil {
		panic(err)
	}
	defer netClient.Close()

	// 构造并发送认证请求
	authReq := AuthRequest{
		Username: "your-username",
		Password: "your-password",
	}
	encoder := json.NewEncoder(netClient)
	if err := encoder.Encode(authReq); err != nil {
		panic(err)
	}

	// 读取服务器的认证响应
	var authResp AuthResponse
	decoder := json.NewDecoder(netClient)
	if err := decoder.Decode(&authResp); err != nil {
		panic(err)
	}
	if !authResp.Success {
		panic("认证失败:" + authResp.Msg)
	}

	// 认证通过后,创建jsonrpc客户端
	jsonClient := jsonrpc.NewClient(netClient)
	defer jsonClient.Close()

	// 执行RPC调用
	var reply string
	someArgs := "your-arguments"
	err = jsonClient.Call("someMethod", someArgs, &reply)
	if err != nil {
		panic(err)
	}

	println(reply)
}

注意事项

  • 实际项目中不要直接用panic处理错误,应该根据业务逻辑做更优雅的错误捕获和处理。
  • 对于HTTP场景,要确认你的JSON-RPC服务的端点路径(示例中是/rpc),以及是否需要其他请求头。
  • 自定义TCP场景下,必须和服务器约定好认证数据的格式和交互流程,上面的示例是基于JSON格式的认证请求,你可能需要根据实际情况调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:41:28