go16.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // +build go1.6,!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. "fmt"
  22. "io"
  23. "net"
  24. "net/http"
  25. "golang.org/x/net/context"
  26. "google.golang.org/grpc/codes"
  27. "google.golang.org/grpc/internal/transport"
  28. "google.golang.org/grpc/status"
  29. )
  30. // dialContext connects to the address on the named network.
  31. func dialContext(ctx context.Context, network, address string) (net.Conn, error) {
  32. return (&net.Dialer{Cancel: ctx.Done()}).Dial(network, address)
  33. }
  34. func sendHTTPRequest(ctx context.Context, req *http.Request, conn net.Conn) error {
  35. req.Cancel = ctx.Done()
  36. if err := req.Write(conn); err != nil {
  37. return fmt.Errorf("failed to write the HTTP request: %v", err)
  38. }
  39. return nil
  40. }
  41. // toRPCErr converts an error into an error from the status package.
  42. func toRPCErr(err error) error {
  43. if err == nil || err == io.EOF {
  44. return err
  45. }
  46. if _, ok := status.FromError(err); ok {
  47. return err
  48. }
  49. switch e := err.(type) {
  50. case transport.StreamError:
  51. return status.Error(e.Code, e.Desc)
  52. case transport.ConnectionError:
  53. return status.Error(codes.Unavailable, e.Desc)
  54. default:
  55. switch err {
  56. case context.DeadlineExceeded:
  57. return status.Error(codes.DeadlineExceeded, err.Error())
  58. case context.Canceled:
  59. return status.Error(codes.Canceled, err.Error())
  60. }
  61. }
  62. return status.Error(codes.Unknown, err.Error())
  63. }