Go JSON-RPC 与路由注册
Go JSON-RPC 与路由注册
在极目桌面架构中,前端与后端交互基于 JSON-RPC 2.0 规范。
1. 注册基础格式
simplejrpc-go 提供了轻量、无反射损耗的函数注册机制:
package handler
import (
"context"
"github.com/dushixiang/simplejrpc-go"
"app/internal/service"
"app/internal/transport/rpc/dto"
)
func RegisterAppHandlers(s *simplejrpc.Server, svc service.DemoService) {
// 获取系统信息
s.RegisterFunc("app.getSystemInfo", func(ctx context.Context, req dto.EmptyReq) (*dto.SystemInfoResp, error) {
return svc.GetSystemInfo(ctx)
})
// 执行任务
s.RegisterFunc("app.executeTask", func(ctx context.Context, req dto.TaskReq) (*dto.TaskResp, error) {
return svc.ExecuteTask(ctx, req)
})
}2. 前端发起调用方式
前端 Vue3 页面通过已注入的 $gm 全局客户端调用上述注册的方法:
// Vue3 Script Setup
import { ref } from 'vue'
const info = ref(null)
const fetchInfo = async () => {
try {
const res = await window.$gm.request({
method: 'app.getSystemInfo',
params: {}
})
info.value = res.data
} catch (err) {
console.error('RPC 请求失败:', err)
}
}3. 标准返回值规范
所有业务接口建议统一包含标准格式结构:
{
"code": 0,
"msg": "success",
"data": {
"version": "1.0.0",
"uptime": 3600
}
}