本文整理汇总了Golang中google/golang.org/grpc.Code函数的典型用法代码示例。如果您正苦于以下问题:Golang Code函数的具体用法?Golang Code怎么用?Golang Code使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Code函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestRemoveUnusedSecret
func TestRemoveUnusedSecret(t *testing.T) {
ts := newTestServer(t)
defer ts.Stop()
// removing a secret without providing an ID results in an InvalidArgument
_, err := ts.Client.RemoveSecret(context.Background(), &api.RemoveSecretRequest{})
assert.Error(t, err)
assert.Equal(t, codes.InvalidArgument, grpc.Code(err), grpc.ErrorDesc(err))
// removing a secret that exists succeeds
secret := secretFromSecretSpec(createSecretSpec("name", []byte("data"), nil))
err = ts.Store.Update(func(tx store.Tx) error {
return store.CreateSecret(tx, secret)
})
assert.NoError(t, err)
resp, err := ts.Client.RemoveSecret(context.Background(), &api.RemoveSecretRequest{SecretID: secret.ID})
assert.NoError(t, err)
assert.Equal(t, api.RemoveSecretResponse{}, *resp)
// ---- it was really removed because attempting to remove it again fails with a NotFound ----
_, err = ts.Client.RemoveSecret(context.Background(), &api.RemoveSecretRequest{SecretID: secret.ID})
assert.Error(t, err)
assert.Equal(t, codes.NotFound, grpc.Code(err), grpc.ErrorDesc(err))
}
示例2: TabletErrorFromGRPC
// TabletErrorFromGRPC returns a ServerError or a
// OperationalError from the gRPC error.
func TabletErrorFromGRPC(err error) error {
if err == nil {
return nil
}
// TODO(aaijazi): Unfortunately, there's no better way to check for a gRPC server
// error (vs a client error).
// See: https://github.com/grpc/grpc-go/issues/319
if !strings.Contains(err.Error(), vterrors.GRPCServerErrPrefix) {
return OperationalError(fmt.Sprintf("vttablet: %v", err))
}
// server side error, convert it
var code int
switch grpc.Code(err) {
case codes.Internal:
code = ERR_FATAL
case codes.FailedPrecondition:
code = ERR_RETRY
case codes.ResourceExhausted:
code = ERR_TX_POOL_FULL
case codes.Aborted:
code = ERR_NOT_IN_TX
default:
code = ERR_NORMAL
}
return &ServerError{
Code: code,
Err: fmt.Sprintf("vttablet: %v", err),
ServerCode: vterrors.GRPCCodeToErrorCode(grpc.Code(err)),
}
}
示例3: doCancelAfterFirstResponse
func doCancelAfterFirstResponse(tc testpb.TestServiceClient) {
ctx, cancel := context.WithCancel(context.Background())
stream, err := tc.FullDuplexCall(ctx)
if err != nil {
grpclog.Fatalf("%v.FullDuplexCall(_) = _, %v", tc, err)
}
respParam := []*testpb.ResponseParameters{
{
Size: proto.Int32(31415),
},
}
pl := newPayload(testpb.PayloadType_COMPRESSABLE, 27182)
req := &testpb.StreamingOutputCallRequest{
ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(),
ResponseParameters: respParam,
Payload: pl,
}
if err := stream.Send(req); err != nil {
grpclog.Fatalf("%v.Send(%v) = %v", stream, req, err)
}
if _, err := stream.Recv(); err != nil {
grpclog.Fatalf("%v.Recv() = %v", stream, err)
}
cancel()
if _, err := stream.Recv(); grpc.Code(err) != codes.Canceled {
grpclog.Fatalf("%v compleled with error code %d, want %d", stream, grpc.Code(err), codes.Canceled)
}
grpclog.Println("CancelAfterFirstResponse done")
}
示例4: TestGetSecret
func TestGetSecret(t *testing.T) {
ts := newTestServer(t)
defer ts.Stop()
// ---- getting a secret without providing an ID results in an InvalidArgument ----
_, err := ts.Client.GetSecret(context.Background(), &api.GetSecretRequest{})
assert.Error(t, err)
assert.Equal(t, codes.InvalidArgument, grpc.Code(err), grpc.ErrorDesc(err))
// ---- getting a non-existent secret fails with NotFound ----
_, err = ts.Client.GetSecret(context.Background(), &api.GetSecretRequest{SecretID: "12345"})
assert.Error(t, err)
assert.Equal(t, codes.NotFound, grpc.Code(err), grpc.ErrorDesc(err))
// ---- getting an existing secret returns the secret with all the private data cleaned ----
secret := secretFromSecretSpec(createSecretSpec("name", []byte("data"), nil))
err = ts.Store.Update(func(tx store.Tx) error {
return store.CreateSecret(tx, secret)
})
assert.NoError(t, err)
resp, err := ts.Client.GetSecret(context.Background(), &api.GetSecretRequest{SecretID: secret.ID})
assert.NoError(t, err)
assert.NotNil(t, resp)
assert.NotNil(t, resp.Secret)
// the data should be empty/omitted
assert.NotEqual(t, secret, resp.Secret)
secret.Spec.Data = nil
assert.Equal(t, secret, resp.Secret)
}
示例5: TestCreateService
func TestCreateService(t *testing.T) {
ts := newTestServer(t)
defer ts.Stop()
_, err := ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{})
assert.Error(t, err)
assert.Equal(t, codes.InvalidArgument, grpc.Code(err))
spec := createSpec("name", "image", 1)
r, err := ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec})
assert.NoError(t, err)
assert.NotEmpty(t, r.Service.ID)
// test port conflicts
spec = createSpec("name2", "image", 1)
spec.Endpoint = &api.EndpointSpec{Ports: []*api.PortConfig{
{PublishedPort: uint32(9000), TargetPort: uint32(9000), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)},
}}
r, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec})
assert.NoError(t, err)
assert.NotEmpty(t, r.Service.ID)
spec2 := createSpec("name3", "image", 1)
spec2.Endpoint = &api.EndpointSpec{Ports: []*api.PortConfig{
{PublishedPort: uint32(9000), TargetPort: uint32(9000), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)},
}}
_, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec2})
assert.Error(t, err)
assert.Equal(t, codes.InvalidArgument, grpc.Code(err))
// test no port conflicts when no publish port is specified
spec3 := createSpec("name4", "image", 1)
spec3.Endpoint = &api.EndpointSpec{Ports: []*api.PortConfig{
{TargetPort: uint32(9000), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)},
}}
r, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec3})
assert.NoError(t, err)
assert.NotEmpty(t, r.Service.ID)
spec4 := createSpec("name5", "image", 1)
spec4.Endpoint = &api.EndpointSpec{Ports: []*api.PortConfig{
{TargetPort: uint32(9001), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)},
}}
_, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec4})
assert.NoError(t, err)
// ensure no port conflict when different protocols are used
spec = createSpec("name6", "image", 1)
spec.Endpoint = &api.EndpointSpec{Ports: []*api.PortConfig{
{PublishedPort: uint32(9100), TargetPort: uint32(9100), Protocol: api.PortConfig_Protocol(api.ProtocolTCP)},
}}
r, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec})
assert.NoError(t, err)
assert.NotEmpty(t, r.Service.ID)
spec2 = createSpec("name7", "image", 1)
spec2.Endpoint = &api.EndpointSpec{Ports: []*api.PortConfig{
{PublishedPort: uint32(9100), TargetPort: uint32(9100), Protocol: api.PortConfig_Protocol(api.ProtocolUDP)},
}}
_, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: spec2})
assert.NoError(t, err)
}
示例6: TestGetCluster
func TestGetCluster(t *testing.T) {
ts := newTestServer(t)
defer ts.Stop()
_, err := ts.Client.GetCluster(context.Background(), &api.GetClusterRequest{})
assert.Error(t, err)
assert.Equal(t, codes.InvalidArgument, grpc.Code(err))
_, err = ts.Client.GetCluster(context.Background(), &api.GetClusterRequest{ClusterID: "invalid"})
assert.Error(t, err)
assert.Equal(t, codes.NotFound, grpc.Code(err))
cluster := createCluster(t, ts, "name", "name", api.AcceptancePolicy{}, ts.Server.rootCA)
r, err := ts.Client.GetCluster(context.Background(), &api.GetClusterRequest{ClusterID: cluster.ID})
assert.NoError(t, err)
cluster.Meta.Version = r.Cluster.Meta.Version
// Only public fields should be available
assert.Equal(t, cluster.ID, r.Cluster.ID)
assert.Equal(t, cluster.Meta, r.Cluster.Meta)
assert.Equal(t, cluster.Spec, r.Cluster.Spec)
assert.Equal(t, cluster.RootCA.CACert, r.Cluster.RootCA.CACert)
assert.Equal(t, cluster.RootCA.CACertHash, r.Cluster.RootCA.CACertHash)
// CAKey and network keys should be nil
assert.Nil(t, r.Cluster.RootCA.CAKey)
assert.Nil(t, r.Cluster.NetworkBootstrapKeys)
}
示例7: DefaultHTTPError
// DefaultHTTPError is the default implementation of HTTPError.
// If "err" is an error from gRPC system, the function replies with the status code mapped by HTTPStatusFromCode.
// If otherwise, it replies with http.StatusInternalServerError.
//
// The response body returned by this function is a JSON object,
// which contains a member whose key is "error" and whose value is err.Error().
func DefaultHTTPError(ctx context.Context, w http.ResponseWriter, _ *http.Request, err error) {
const fallback = `{"error": "failed to marshal error message"}`
w.Header().Del("Trailer")
w.Header().Set("Content-Type", "application/json")
body := errorBody{
Error: grpc.ErrorDesc(err),
Code: int(grpc.Code(err)),
}
buf, merr := json.Marshal(body)
if merr != nil {
grpclog.Printf("Failed to marshal error message %q: %v", body, merr)
w.WriteHeader(http.StatusInternalServerError)
if _, err := io.WriteString(w, fallback); err != nil {
grpclog.Printf("Failed to write response: %v", err)
}
return
}
md, ok := ServerMetadataFromContext(ctx)
if !ok {
grpclog.Printf("Failed to extract ServerMetadata from context")
}
handleForwardResponseServerMetadata(w, md)
st := HTTPStatusFromCode(grpc.Code(err))
w.WriteHeader(st)
if _, err := w.Write(buf); err != nil {
grpclog.Printf("Failed to write response: %v", err)
}
handleForwardResponseTrailer(w, md)
}
示例8: checkRPCError
func checkRPCError(err error, code codes.Code, message string) error {
if g, e := grpc.Code(err), code; g != e {
return fmt.Errorf("wrong grpc error code: %v != %v", g, e)
}
// TODO https://github.com/grpc/grpc-go/issues/110
if g, e := err.Error(), fmt.Sprintf("rpc error: code = %d desc = %q", grpc.Code(err), message); g != e {
return fmt.Errorf("wrong error message: %v != %v", g, e)
}
return nil
}
示例9: DoCancelAfterBegin
// DoCancelAfterBegin cancels the RPC after metadata has been sent but before payloads are sent.
func DoCancelAfterBegin(tc testpb.TestServiceClient) {
ctx, cancel := context.WithCancel(metadata.NewContext(context.Background(), testMetadata))
stream, err := tc.StreamingInputCall(ctx)
if err != nil {
grpclog.Fatalf("%v.StreamingInputCall(_) = _, %v", tc, err)
}
cancel()
_, err = stream.CloseAndRecv()
if grpc.Code(err) != codes.Canceled {
grpclog.Fatalf("%v.CloseAndRecv() got error code %d, want %d", stream, grpc.Code(err), codes.Canceled)
}
}
示例10: IsClosedConnection
// IsClosedConnection returns true if err is an error produced by gRPC on closed connections.
func IsClosedConnection(err error) bool {
if err == context.Canceled ||
grpc.Code(err) == codes.Canceled ||
grpc.Code(err) == codes.Unavailable ||
grpc.ErrorDesc(err) == grpc.ErrClientConnClosing.Error() ||
strings.Contains(err.Error(), "is closing") ||
strings.Contains(err.Error(), "node unavailable") {
return true
}
if streamErr, ok := err.(transport.StreamError); ok && streamErr.Code == codes.Canceled {
return true
}
return netutil.IsClosedConnection(err)
}
示例11: TestRemoveUsedSecret
func TestRemoveUsedSecret(t *testing.T) {
ts := newTestServer(t)
defer ts.Stop()
// Create two secrets
data := []byte("secret")
creationSpec := createSecretSpec("secretID1", data, nil)
resp, err := ts.Client.CreateSecret(context.Background(), &api.CreateSecretRequest{Spec: creationSpec})
assert.NoError(t, err)
creationSpec2 := createSecretSpec("secretID2", data, nil)
resp2, err := ts.Client.CreateSecret(context.Background(), &api.CreateSecretRequest{Spec: creationSpec2})
assert.NoError(t, err)
// Create a service that uses a secret
service := createSpec("service1", "image", 1)
secretRefs := []*api.SecretReference{
{
SecretName: resp.Secret.Spec.Annotations.Name,
SecretID: resp.Secret.ID,
Target: &api.SecretReference_File{
File: &api.SecretReference_FileTarget{
Name: "target.txt",
},
},
},
}
service.Task.GetContainer().Secrets = secretRefs
_, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: service})
assert.NoError(t, err)
service2 := createSpec("service2", "image", 1)
service2.Task.GetContainer().Secrets = secretRefs
_, err = ts.Client.CreateService(context.Background(), &api.CreateServiceRequest{Spec: service2})
assert.NoError(t, err)
// removing a secret that exists but is in use fails
_, err = ts.Client.RemoveSecret(context.Background(), &api.RemoveSecretRequest{SecretID: resp.Secret.ID})
assert.Equal(t, codes.InvalidArgument, grpc.Code(err), grpc.ErrorDesc(err))
assert.Regexp(t, "service[1-2], service[1-2]", grpc.ErrorDesc(err))
// removing a secret that exists but is not in use succeeds
_, err = ts.Client.RemoveSecret(context.Background(), &api.RemoveSecretRequest{SecretID: resp2.Secret.ID})
assert.NoError(t, err)
// it was really removed because attempting to remove it again fails with a NotFound
_, err = ts.Client.RemoveSecret(context.Background(), &api.RemoveSecretRequest{SecretID: resp2.Secret.ID})
assert.Error(t, err)
assert.Equal(t, codes.NotFound, grpc.Code(err), grpc.ErrorDesc(err))
}
示例12: Check
func (p *raftProxyHealthServer) Check(ctx context.Context, r *HealthCheckRequest) (*HealthCheckResponse, error) {
if p.cluster.IsLeader() {
return p.local.Check(ctx, r)
}
ctx, err := p.runCtxMods(ctx)
if err != nil {
return nil, err
}
conn, err := p.connSelector.Conn()
if err != nil {
return nil, err
}
defer func() {
if err != nil {
errStr := err.Error()
if strings.Contains(errStr, grpc.ErrClientConnClosing.Error()) ||
strings.Contains(errStr, grpc.ErrClientConnTimeout.Error()) ||
strings.Contains(errStr, "connection error") ||
grpc.Code(err) == codes.Internal {
p.connSelector.Reset()
}
}
}()
return NewHealthClient(conn).Check(ctx, r)
}
示例13: TestLanguageServiceAnnotateTextError
func TestLanguageServiceAnnotateTextError(t *testing.T) {
errCode := codes.Internal
mockLanguage.err = grpc.Errorf(errCode, "test error")
var document *languagepb.Document = &languagepb.Document{}
var features *languagepb.AnnotateTextRequest_Features = &languagepb.AnnotateTextRequest_Features{}
var encodingType languagepb.EncodingType = 0
var request = &languagepb.AnnotateTextRequest{
Document: document,
Features: features,
EncodingType: encodingType,
}
c, err := NewClient(context.Background(), clientOpt)
if err != nil {
t.Fatal(err)
}
resp, err := c.AnnotateText(context.Background(), request)
if c := grpc.Code(err); c != errCode {
t.Errorf("got error code %q, want %q", c, errCode)
}
_ = resp
}
示例14: unwrapError
func unwrapError(err error) error {
code := grpc.Code(err)
errBody := grpc.ErrorDesc(err)
switch code {
case InternalServerError:
return core.InternalServerError(errBody)
case NotSupportedError:
return core.NotSupportedError(errBody)
case MalformedRequestError:
return core.MalformedRequestError(errBody)
case UnauthorizedError:
return core.UnauthorizedError(errBody)
case NotFoundError:
return core.NotFoundError(errBody)
case SignatureValidationError:
return core.SignatureValidationError(errBody)
case NoSuchRegistrationError:
return core.NoSuchRegistrationError(errBody)
case RateLimitedError:
return core.RateLimitedError(errBody)
case LengthRequiredError:
return core.LengthRequiredError(errBody)
case BadNonceError:
return core.BadNonceError(errBody)
default:
return err
}
}
示例15: testCancel
func testCancel(t *testing.T, e env) {
s, addr := serverSetUp(t, nil, math.MaxUint32, nil, nil, e)
cc := clientSetUp(t, addr, nil, nil, "", e)
tc := testpb.NewTestServiceClient(cc)
defer tearDown(s, cc)
argSize := 2718
respSize := 314
payload, err := newPayload(testpb.PayloadType_COMPRESSABLE, int32(argSize))
if err != nil {
t.Fatal(err)
}
req := &testpb.SimpleRequest{
ResponseType: testpb.PayloadType_COMPRESSABLE.Enum(),
ResponseSize: proto.Int32(int32(respSize)),
Payload: payload,
}
ctx, cancel := context.WithCancel(context.Background())
time.AfterFunc(1*time.Millisecond, cancel)
reply, err := tc.UnaryCall(ctx, req)
if grpc.Code(err) != codes.Canceled {
t.Fatalf(`TestService/UnaryCall(_, _) = %v, %v; want <nil>, error code: %d`, reply, err, codes.Canceled)
}
}