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