go17.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // +build go1.7
  2. /*
  3. *
  4. * Copyright 2016 gRPC authors.
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. *
  18. */
  19. package grpc
  20. import (
  21. "context"
  22. "fmt"
  23. "io"
  24. "net"
  25. "net/http"
  26. netctx "golang.org/x/net/context"
  27. "google.golang.org/grpc/codes"
  28. "google.golang.org/grpc/internal/transport"
  29. "google.golang.org/grpc/status"
  30. )
  31. // dialContext connects to the address on the named network.
  32. func dialContext(ctx context.Context, network, address string) (net.Conn, error) {
  33. return (&net.Dialer{}).DialContext(ctx, network, address)
  34. }
  35. func sendHTTPRequest(ctx context.Context, req *http.Request, conn net.Conn) error {
  36. req = req.WithContext(ctx)
  37. if err := req.Write(conn); err != nil {
  38. return fmt.Errorf("failed to write the HTTP request: %v", err)
  39. }
  40. return nil
  41. }
  42. // toRPCErr converts an error into an error from the status package.
  43. func toRPCErr(err error) error {
  44. if err == nil || err == io.EOF {
  45. return err
  46. }
  47. if _, ok := status.FromError(err); ok {
  48. return err
  49. }
  50. switch e := err.(type) {
  51. case transport.StreamError:
  52. return status.Error(e.Code, e.Desc)
  53. case transport.ConnectionError:
  54. return status.Error(codes.Unavailable, e.Desc)
  55. default:
  56. switch err {
  57. case context.DeadlineExceeded, netctx.DeadlineExceeded:
  58. return status.Error(codes.DeadlineExceeded, err.Error())
  59. case context.Canceled, netctx.Canceled:
  60. return status.Error(codes.Canceled, err.Error())
  61. }
  62. }
  63. return status.Error(codes.Unknown, err.Error())
  64. }