You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

86 lines
2.4 KiB

  1. // Copyright 2016 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package internal
  15. import (
  16. "bytes"
  17. "context"
  18. "io"
  19. "log"
  20. "google.golang.org/grpc"
  21. "google.golang.org/grpc/codes"
  22. )
  23. type ExampleReadHandler struct {
  24. buf []byte
  25. name string // In this example, the service can handle one name only.
  26. }
  27. func (mr *ExampleReadHandler) GetReader(ctx context.Context, name string) (io.ReaderAt, error) {
  28. if mr.name == "" {
  29. mr.name = name
  30. log.Printf("read from name: %q", name)
  31. } else if mr.name != name {
  32. return nil, grpc.Errorf(codes.NotFound, "reader has name %q, name %q not allowed", mr.name, name)
  33. }
  34. return bytes.NewReader(mr.buf), nil
  35. }
  36. // Close can be a no-op.
  37. func (mr *ExampleReadHandler) Close(ctx context.Context, name string) error {
  38. return nil
  39. }
  40. type ExampleWriteHandler struct {
  41. buf bytes.Buffer // bytes.Buffer implements io.Writer
  42. name string // In this example, the service can handle one name only.
  43. }
  44. // Handle writes to a given name.
  45. func (mw *ExampleWriteHandler) GetWriter(ctx context.Context, name string, initOffset int64) (io.Writer, error) {
  46. if mw.name == "" {
  47. mw.name = name
  48. log.Printf("write to name: %q", name)
  49. } else if mw.name != name {
  50. return nil, grpc.Errorf(codes.NotFound, "reader has name %q, name=%q not allowed", mw.name, name)
  51. }
  52. // TODO: initOffset is ignored.
  53. return &mw.buf, nil
  54. }
  55. // Close can be a no-op.
  56. func (mw *ExampleWriteHandler) Close(ctx context.Context, name string) error {
  57. return nil
  58. }
  59. func ExampleNewServer() {
  60. reader := &ExampleReadHandler{
  61. buf: []byte("Hello World!"),
  62. name: "foo",
  63. }
  64. writer := &ExampleWriteHandler{}
  65. gsrv := grpc.NewServer()
  66. bytestreamServer, err := NewServer(gsrv, reader, writer)
  67. if err != nil {
  68. log.Printf("NewServer: %v", err)
  69. return
  70. }
  71. // Start accepting incoming connections.
  72. // See gRPC docs and newGRPCServer in google.golang.org/api/transport/bytestream/client_test.go.
  73. _ = bytestreamServer
  74. }