Procházet zdrojové kódy

新增jsonrpc2.ParseResponse函数

niujiuru před 2 týdny
rodič
revize
391cc10d38
1 změnil soubory, kde provedl 37 přidání a 0 odebrání
  1. 37 0
      utils/jsonrpc2/rpc.go

+ 37 - 0
utils/jsonrpc2/rpc.go

@@ -73,6 +73,43 @@ func ParseRequest(input any) (*Request, error) {
 	return &req, nil
 }
 
+// 解析应答数据
+func ParseResponse(input any) (*Response, error) {
+	var raw []byte
+
+	switch v := input.(type) {
+	case nil:
+		return nil, errors.New("input is nil")
+	case string:
+		raw = []byte(v)
+	case []byte:
+		raw = v
+	default:
+		return nil, errors.New("unsupported input type: must be string or []byte")
+	}
+
+	var resp Response
+	if err := json.Unmarshal(raw, &resp); err != nil {
+		return nil, fmt.Errorf("unmarshal response: %w", err)
+	}
+
+	if resp.ID == nil {
+		if resp.Error == nil || resp.Error.Code != ErrParse {
+			return nil, errors.New(`response must contain an "id" field`)
+		}
+	}
+
+	if resp.Error == nil && resp.Result == nil {
+		return nil, errors.New(`response must contain either "result" or "error" field`)
+	}
+
+	if resp.Error != nil && resp.Result != nil {
+		return nil, errors.New(`response can't contain both "result" and "error" field`)
+	}
+
+	return &resp, nil
+}
+
 // 编码JSON数据
 func marshalJSON(input any) (json.RawMessage, error) {
 	switch v := input.(type) {