当前位置: 首页>>代码示例>>Golang>>正文


Golang json.Register函数代码示例

本文整理汇总了Golang中github.com/uber/tchannel-go/json.Register函数的典型用法代码示例。如果您正苦于以下问题:Golang Register函数的具体用法?Golang Register怎么用?Golang Register使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Register函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: main

func main() {
	// Create a new TChannel for handling requests
	ch, err := tchannel.NewChannel("PingService", &tchannel.ChannelOptions{Logger: tchannel.SimpleLogger})
	if err != nil {
		log.WithFields(tchannel.ErrField(err)).Fatal("Couldn't create new channel.")
	}

	// Register a handler for the ping message on the PingService
	json.Register(ch, json.Handlers{
		"ping": pingHandler,
	}, onError)

	// Listen for incoming requests
	listenAndHandle(ch, "127.0.0.1:10500")

	// Create a new TChannel for sending requests.
	client, err := tchannel.NewChannel("ping-client", nil)
	if err != nil {
		log.WithFields(tchannel.ErrField(err)).Fatal("Couldn't create new client channel.")
	}

	// Make a call to ourselves, with a timeout of 10s
	ctx, cancel := json.NewContext(time.Second * 10)
	defer cancel()

	peer := client.Peers().Add(ch.PeerInfo().HostPort)

	var pong Pong
	if err := json.CallPeer(ctx, peer, "PingService", "ping", &Ping{"Hello World"}, &pong); err != nil {
		log.WithFields(tchannel.ErrField(err)).Fatal("json.Call failed.")
	}

	log.Infof("Received pong: %s", pong.Message)

	// Create a new subchannel for the top-level channel
	subCh := ch.GetSubChannel("PingServiceOther")

	// Register a handler on the subchannel
	json.Register(subCh, json.Handlers{
		"pingOther": pingOtherHandler,
	}, onError)

	// Try to send a message to the Service:Method pair for the subchannel
	if err := json.CallPeer(ctx, peer, "PingServiceOther", "pingOther", &Ping{"Hello Other World"}, &pong); err != nil {
		log.WithFields(tchannel.ErrField(err)).Fatal("json.Call failed.")
	}

	log.Infof("Received pong: %s", pong.Message)
}
开发者ID:gosuper,项目名称:tchannel-go,代码行数:49,代码来源:main.go

示例2: TestTracingPropagates

func TestTracingPropagates(t *testing.T) {
	WithVerifiedServer(t, nil, func(ch *Channel, hostPort string) {
		handler := &traceHandler{t: t, ch: ch}
		json.Register(ch, json.Handlers{
			"call": handler.call,
		}, handler.onError)

		ctx, cancel := json.NewContext(time.Second)
		defer cancel()

		peer := ch.Peers().GetOrAdd(ch.PeerInfo().HostPort)
		var response TracingResponse
		require.NoError(t, json.CallPeer(ctx, peer, ch.PeerInfo().ServiceName, "call", &TracingRequest{
			ForwardCount: 1,
		}, &response))

		clientSpan := CurrentSpan(ctx)
		require.NotNil(t, clientSpan)
		assert.Equal(t, uint64(0), clientSpan.ParentID())
		assert.NotEqual(t, uint64(0), clientSpan.TraceID())
		assert.True(t, clientSpan.TracingEnabled(), "Tracing should be enabled")
		assert.Equal(t, clientSpan.TraceID(), response.TraceID)
		assert.Equal(t, clientSpan.SpanID(), response.ParentID)
		assert.True(t, response.TracingEnabled, "Tracing should be enabled")
		assert.Equal(t, response.TraceID, response.SpanID, "traceID = spanID for root span")

		nestedResponse := response.Child
		require.NotNil(t, nestedResponse)
		assert.Equal(t, clientSpan.TraceID(), nestedResponse.TraceID)
		assert.Equal(t, response.SpanID, nestedResponse.ParentID)
		assert.True(t, response.TracingEnabled, "Tracing should be enabled")
		assert.NotEqual(t, response.SpanID, nestedResponse.SpanID)
	})
}
开发者ID:glycerine,项目名称:tchannel-go,代码行数:34,代码来源:tracing_test.go

示例3: runRetryTest

func runRetryTest(t *testing.T, f func(r *retryTest)) {
	r := &retryTest{}
	defer testutils.SetTimeout(t, time.Second)()
	r.setup()
	defer testutils.ResetSleepStub(&timeSleep)

	withSetup(t, func(hypCh *tchannel.Channel, hostPort string) {
		json.Register(hypCh, json.Handlers{"ad": r.adHandler}, nil)

		// Advertise failures cause warning log messages.
		opts := testutils.NewOpts().
			SetServiceName("my-client").
			AddLogFilter("Hyperbahn client registration failed", 10)
		serverCh := testutils.NewServer(t, opts)
		defer serverCh.Close()

		var err error
		r.ch = serverCh
		r.client, err = NewClient(serverCh, configFor(hostPort), &ClientOptions{
			Handler:      r,
			FailStrategy: FailStrategyIgnore,
		})
		require.NoError(t, err, "NewClient")
		defer r.client.Close()
		f(r)
		r.mock.AssertExpectations(t)
	})
}
开发者ID:gosuper,项目名称:tchannel-go,代码行数:28,代码来源:advertise_test.go

示例4: TestInitialAdvertiseFailedRetryTimeout

func TestInitialAdvertiseFailedRetryTimeout(t *testing.T) {
	withSetup(t, func(hypCh *tchannel.Channel, hyperbahnHostPort string) {
		started := time.Now()
		count := 0
		adHandler := func(ctx json.Context, req *AdRequest) (*AdResponse, error) {
			count++

			deadline, ok := ctx.Deadline()
			if assert.True(t, ok, "context is missing Deadline") {
				assert.True(t, deadline.Sub(started) <= 2*time.Second,
					"Timeout per attempt should be 1 second. Started: %v Deadline: %v", started, deadline)
			}

			return nil, tchannel.NewSystemError(tchannel.ErrCodeUnexpected, "unexpected")
		}
		json.Register(hypCh, json.Handlers{"ad": adHandler}, nil)

		ch := testutils.NewServer(t, nil)
		client, err := NewClient(ch, configFor(hyperbahnHostPort), stubbedSleep())
		assert.NoError(t, err, "hyperbahn NewClient failed")
		defer client.Close()

		assert.Error(t, client.Advertise(), "Advertise should not succeed")
		// We expect 5 retries by TChannel and we attempt 5 to advertise 5 times.
		assert.Equal(t, 5*5, count, "adHandler not retried correct number of times")
	})
}
开发者ID:uber,项目名称:tchannel-go,代码行数:27,代码来源:advertise_test.go

示例5: TestInboundExistingMethods

func TestInboundExistingMethods(t *testing.T) {
	// Create a channel with an existing "echo" method.
	ch, err := tchannel.NewChannel("foo", nil)
	require.NoError(t, err)
	json.Register(ch, json.Handlers{
		"echo": func(ctx json.Context, req map[string]string) (map[string]string, error) {
			return req, nil
		},
	}, nil)

	i := NewInbound(ch)
	service := transport.ServiceDetail{Name: "derp", Registry: new(transporttest.MockRegistry)}
	require.NoError(t, i.Start(service, transport.NoDeps))
	defer i.Stop()

	// Make a call to the "echo" method which should call our pre-registered method.
	ctx, cancel := json.NewContext(time.Second)
	defer cancel()

	var resp map[string]string
	arg := map[string]string{"k": "v"}

	svc := ch.ServiceName()
	peer := ch.Peers().GetOrAdd(ch.PeerInfo().HostPort)
	err = json.CallPeer(ctx, peer, svc, "echo", arg, &resp)
	require.NoError(t, err, "Call failed")
	assert.Equal(t, arg, resp, "Response mismatch")
}
开发者ID:yarpc,项目名称:yarpc-go,代码行数:28,代码来源:inbound_test.go

示例6: TestJSONTracingPropagation

func TestJSONTracingPropagation(t *testing.T) {
	suite := &PropagationTestSuite{
		Encoding: EncodingInfo{Format: tchannel.JSON, HeadersSupported: true},
		Register: func(t *testing.T, ch *tchannel.Channel) TracingCall {
			handler := &JSONHandler{TraceHandler: TraceHandler{Ch: ch}, t: t}
			json.Register(ch, json.Handlers{"call": handler.callJSON}, handler.onError)
			return handler.firstCall
		},
		TestCases: map[TracerType][]PropagationTestCase{
			Noop: {
				{ForwardCount: 2, TracingDisabled: true, ExpectedBaggage: "", ExpectedSpanCount: 0},
				{ForwardCount: 2, TracingDisabled: false, ExpectedBaggage: "", ExpectedSpanCount: 0},
			},
			Mock: {
				{ForwardCount: 2, TracingDisabled: true, ExpectedBaggage: BaggageValue, ExpectedSpanCount: 0},
				{ForwardCount: 2, TracingDisabled: false, ExpectedBaggage: BaggageValue, ExpectedSpanCount: 6},
			},
			Jaeger: {
				{ForwardCount: 2, TracingDisabled: true, ExpectedBaggage: BaggageValue, ExpectedSpanCount: 0},
				{ForwardCount: 2, TracingDisabled: false, ExpectedBaggage: BaggageValue, ExpectedSpanCount: 6},
			},
		},
	}
	suite.Run(t)
}
开发者ID:uber,项目名称:tchannel-go,代码行数:25,代码来源:tracing_test.go

示例7: registerPong

func (s *ForwarderTestSuite) registerPong(address string, channel *tchannel.Channel) {
	hmap := map[string]interface{}{
		"/ping": func(ctx json.Context, ping *Ping) (*Pong, error) {
			return &Pong{"Hello, world!", address}, nil
		},
		"/error": func(ctx json.Context, ping *Ping) (*Pong, error) {
			return nil, errors.New("remote error")
		},
	}
	s.Require().NoError(json.Register(channel, hmap, func(ctx context.Context, err error) {}))

	thriftHandler := &pingpong.MockTChanPingPong{}

	// successful request
	thriftHandler.On("Ping", mock.Anything, &pingpong.Ping{
		Key: "success",
	}).Return(&pingpong.Pong{
		Source: address,
	}, nil)

	// error request
	thriftHandler.On("Ping", mock.Anything, &pingpong.Ping{
		Key: "error",
	}).Return(nil, &pingpong.PingError{})

	server := thrift.NewServer(channel)
	server.Register(pingpong.NewTChanPingPongServer(thriftHandler))
}
开发者ID:dansimau,项目名称:ringpop-go,代码行数:28,代码来源:forwarder_test.go

示例8: RegisterPong

func (w *worker) RegisterPong() error {
	hmap := map[string]interface{}{"/ping": w.PingHandler}

	return json.Register(w.channel, hmap, func(ctx context.Context, err error) {
		w.logger.Debug("error occured: %v", err)
	})
}
开发者ID:dansimau,项目名称:ringpop-go,代码行数:7,代码来源:main.go

示例9: registerHandlers

func (rp *Ringpop) registerHandlers() error {
	handlers := map[string]interface{}{
		"/health":       rp.health,
		"/admin/stats":  rp.adminStatsHandler,
		"/admin/lookup": rp.adminLookupHandler,
	}

	return json.Register(rp.channel, handlers, func(ctx context.Context, err error) {
		rp.log.WithField("error", err).Info("error occured")
	})
}
开发者ID:coderQQ,项目名称:ringpop-go,代码行数:11,代码来源:handlers.go

示例10: register

// Register the different endpoints of the test subject
func register(ch *tchannel.Channel) {
	ch.Register(raw.Wrap(echoRawHandler{}), "echo/raw")
	ch.Register(raw.Wrap(handlerTimeoutRawHandler{}), "handlertimeout/raw")

	json.Register(ch, json.Handlers{"echo": echoJSONHandler}, onError)

	tserver := thrift.NewServer(ch)
	tserver.Register(echo.NewTChanEchoServer(&echoThriftHandler{}))
	tserver.Register(gauntlet_tchannel.NewTChanThriftTestServer(&thriftTestHandler{}))
	tserver.Register(gauntlet_tchannel.NewTChanSecondServiceServer(&secondServiceHandler{}))
}
开发者ID:yarpc,项目名称:yarpc-go,代码行数:12,代码来源:server.go

示例11: RegisterHandler

func (s *ReplicatorTestSuite) RegisterHandler(ch shared.SubChannel, address string) {
	handler := map[string]interface{}{
		"/ping": func(ctx json.Context, ping *Ping) (*Pong, error) {
			s.Equal(ping.From, "127.0.0.1:3001")
			return &Pong{"Hello, world!", address}, nil
		},
	}

	s.Require().NoError(json.Register(ch, handler, func(ctx context.Context, err error) {
		s.Fail("calls shouldn't fail")
	}))
}
开发者ID:gl-works,项目名称:ringpop-go,代码行数:12,代码来源:replicator_test.go

示例12: TestNotListeningChannel

func TestNotListeningChannel(t *testing.T) {
	withSetup(t, func(hypCh *tchannel.Channel, hyperbahnHostPort string) {
		adHandler := func(ctx json.Context, req *AdRequest) (*AdResponse, error) {
			return &AdResponse{1}, nil
		}
		json.Register(hypCh, json.Handlers{"ad": adHandler}, nil)

		ch := testutils.NewClient(t, nil)
		client, err := NewClient(ch, configFor(hyperbahnHostPort), nil)
		assert.NoError(t, err, "hyperbahn NewClient failed")
		defer client.Close()

		assert.Equal(t, errEphemeralPeer, client.Advertise(), "Advertise without Listen should fail")
	})
}
开发者ID:gosuper,项目名称:tchannel-go,代码行数:15,代码来源:advertise_test.go

示例13: New

// New returns a mock Hyperbahn server that can be used for testing.
func New() (*Mock, error) {
	ch, err := tchannel.NewChannel("hyperbahn", nil)
	if err != nil {
		return nil, err
	}

	mh := &Mock{
		ch:     ch,
		respCh: make(chan int),
	}
	if err := json.Register(ch, json.Handlers{"ad": mh.adHandler}, nil); err != nil {
		return nil, err
	}

	return mh, ch.ListenAndServe("127.0.0.1:0")
}
开发者ID:dansimau,项目名称:ringpop-go,代码行数:17,代码来源:hyperbahn.go

示例14: TestZipkinTraceReporterFactory

func TestZipkinTraceReporterFactory(t *testing.T) {
	ch, err := tchannel.NewChannel("svc", &tchannel.ChannelOptions{
		TraceReporterFactory: ZipkinTraceReporterFactory,
	})
	assert.NoError(t, err)

	// Create a TCollector channel, and add it as a peer to ch so Report works.
	mockServer := new(mocks.TChanTCollector)
	tcollectorCh, err := setupServer(mockServer)
	require.NoError(t, err, "setupServer failed")
	ch.Peers().Add(tcollectorCh.PeerInfo().HostPort)

	called := make(chan int)
	ret := &gen.Response{Ok: true}
	mockServer.On("Submit", mock.Anything, mock.Anything).Return(ret, nil).Run(func(args mock.Arguments) {
		called <- 1
	})

	// Make some calls, and validate that the trace reporter is not called recursively.
	require.NoError(t, json.Register(tcollectorCh, json.Handlers{"op": func(ctx json.Context, arg map[string]interface{}) (map[string]interface{}, error) {
		return arg, nil
	}}, nil), "Register failed")
	ctx, cancel := json.NewContext(time.Second)
	defer cancel()
	for i := 0; i < 5; i++ {
		var res map[string]string
		assert.NoError(t, json.CallSC(ctx, ch.GetSubChannel(tcollectorServiceName), "op", nil, &res), "call failed")
	}

	// Verify the spans being reported.
	for i := 0; i < 5; i++ {
		select {
		case <-called:
		case <-time.After(time.Second):
			t.Errorf("Expected submit for call %v", i)
		}
	}

	// Verify that no other spans are reported.
	select {
	case <-called:
		t.Errorf("Too many spans reported")
	case <-time.After(time.Millisecond):
	}
}
开发者ID:glycerine,项目名称:tchannel-go,代码行数:45,代码来源:zipkin_tracereporter_test.go

示例15: registerHandlers

func (n *Node) registerHandlers() error {
	handlers := map[string]interface{}{
		"/protocol/join":      n.joinHandler,
		"/protocol/ping":      n.pingHandler,
		"/protocol/ping-req":  n.pingRequestHandler,
		"/admin/debugSet":     notImplementedHandler,
		"/admin/debugClear":   notImplementedHandler,
		"/admin/gossip":       n.gossipHandler, // Deprecated
		"/admin/gossip/start": n.gossipHandlerStart,
		"/admin/gossip/stop":  n.gossipHandlerStop,
		"/admin/tick":         n.tickHandler, // Deprecated
		"/admin/gossip/tick":  n.tickHandler,
		"/admin/member/leave": n.adminLeaveHandler,
		"/admin/member/join":  n.adminJoinHandler,
	}

	return json.Register(n.channel, handlers, n.errorHandler)
}
开发者ID:dansimau,项目名称:ringpop-go,代码行数:18,代码来源:handlers.go


注:本文中的github.com/uber/tchannel-go/json.Register函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。