GrpcImp.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /**
  2. * Tencent is pleased to support the open source community by making Tars available.
  3. *
  4. * Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved.
  5. *
  6. * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
  7. * in compliance with the License. You may obtain a copy of the License at
  8. *
  9. * https://opensource.org/licenses/BSD-3-Clause
  10. *
  11. * Unless required by applicable law or agreed to in writing, software distributed
  12. * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  13. * CONDITIONS OF ANY KIND, either express or implied. See the License for the
  14. * specific language governing permissions and limitations under the License.
  15. */
  16. #include "GrpcImp.h"
  17. #include "servant/Application.h"
  18. #include "helloworld.pb.h"
  19. #include "GrpcServer.h"
  20. using namespace std;
  21. //////////////////////////////////////////////////////
  22. void GrpcImp::initialize()
  23. {
  24. //initialize servant here:
  25. //...
  26. }
  27. //////////////////////////////////////////////////////
  28. void GrpcImp::destroy()
  29. {
  30. //destroy servant here:
  31. //...
  32. }
  33. int GrpcImp::doRequest(TarsCurrentPtr current, vector<char> &buffer)
  34. {
  35. shared_ptr<TC_GrpcServer> session = TC_GrpcServer::getHttp2(current->getUId());
  36. vector<shared_ptr<TC_GrpcServer::Http2Context>> contexts = session->decodeRequest();
  37. for(size_t i = 0; i< contexts.size(); ++i)
  38. {
  39. shared_ptr<TC_GrpcServer::Http2Context> context = contexts[i];
  40. std::string content = context->request.getContent();
  41. bool compressed;
  42. RemoveGrpcPrefix(content, &compressed);
  43. string path = context->request.getHeader(":path");
  44. if (path == "/helloworld.Greeter/SayHello") {
  45. vector<char> data;
  46. helloworld::HelloReply reply;
  47. helloworld::HelloRequest request;
  48. request.ParseFromString(content);
  49. TLOGDEBUG("doRequest request: " << request.name() << endl);
  50. reply.set_message("Hello " + request.name());
  51. string message = reply.SerializeAsString();
  52. addGrpcPrefix(message, false);
  53. session->packGrpcResponse(context, 200, message);
  54. int ret = session->encodeResponse(context, "0", data);
  55. if(ret != 0)
  56. {
  57. cout << "encodeResponse error:" << session->getErrMsg() << endl;
  58. }
  59. buffer.insert(buffer.end(), data.begin(), data.end());
  60. }
  61. }
  62. return 0;
  63. }
  64. int GrpcImp::doClose(TarsCurrentPtr current)
  65. {
  66. TC_GrpcServer::delHttp2(current->getUId());
  67. return 0;
  68. }