HelloWorld.swift 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /*
  2. * Copyright 2024, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Foundation
  17. import GRPCCore
  18. struct HelloWorld: RegistrableRPCService {
  19. static let serviceDescriptor = ServiceDescriptor(package: "helloworld", service: "HelloWorld")
  20. func sayHello(
  21. _ request: ServerRequest<[UInt8]>
  22. ) async throws -> ServerResponse<[UInt8]> {
  23. let name = String(bytes: request.message, encoding: .utf8) ?? "world"
  24. return ServerResponse(message: Array("Hello, \(name)!".utf8), metadata: [])
  25. }
  26. func registerMethods<Transport: ServerTransport>(with router: inout RPCRouter<Transport>) {
  27. let serializer = IdentitySerializer()
  28. let deserializer = IdentityDeserializer()
  29. router.registerHandler(
  30. forMethod: Methods.sayHello,
  31. deserializer: deserializer,
  32. serializer: serializer
  33. ) { streamRequest, context in
  34. let singleRequest = try await ServerRequest(stream: streamRequest)
  35. let singleResponse = try await self.sayHello(singleRequest)
  36. return StreamingServerResponse(single: singleResponse)
  37. }
  38. }
  39. enum Methods {
  40. static let sayHello = MethodDescriptor(
  41. fullyQualifiedService: HelloWorld.serviceDescriptor.fullyQualifiedService,
  42. method: "SayHello"
  43. )
  44. }
  45. }