使用multipart打造rest粗接口
粗接口设计是实现微服务的关键。不论二进制还是rest接口,都可以设计“粗接口”。
使用multipart,可以方便地打造REST粗接口。粗接口设计后的REST API,在各服务间有且只有一个接口。
function restfunc(const AReq: TBytes; const ABoundary: string): TBytes; begin var parts: THttpMultiPartFormData := THttpMultiPartFormData.Create; try try parts.InitWithBoundary(ABoundary); parts.Decode(AReq, Length(AReq)); case StrToIntDef(parts.Fields['cmd'].AsString, 0) of cmd_query: Result := query(parts); end; except on e: Exception do WriteLog('yn.restfunc.restfunc ' + E.Message); end; finally parts.Free; end; end;
procedure TForm2.Button2Click(Sender: TObject); //rest query begin var req: TIdMultiPartFormDataStream := TIdMultiPartFormDataStream.Create; req.AddFormField('cmd', IntToStr(cmd_query)); req.AddFormField('accountno', '1'); req.AddFormField('sql', 'select * from tgoods'); Memo1.Text := IdHTTP1.Post(FUrl + '/rest', req); req.Free; end;