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


Golang http.NewClient函数代码示例

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


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

示例1: New

// New returns an AddService that's backed by the URL. baseurl will have its
// scheme and hostport used, but its path will be overwritten. If client is
// nil, http.DefaultClient will be used.
func New(ctx context.Context, baseurl *url.URL, logger log.Logger, c *http.Client) server.AddService {
	sumURL, err := url.Parse(baseurl.String())
	if err != nil {
		panic(err)
	}
	concatURL, err := url.Parse(baseurl.String())
	if err != nil {
		panic(err)
	}
	sumURL.Path = "/sum"
	concatURL.Path = "/concat"
	return client{
		Context: ctx,
		Logger:  logger,
		sum: httptransport.NewClient(
			"GET",
			sumURL,
			server.EncodeSumRequest,
			server.DecodeSumResponse,
		).Endpoint(),
		concat: httptransport.NewClient(
			"GET",
			concatURL,
			server.EncodeConcatRequest,
			server.DecodeConcatResponse,
		).Endpoint(),
	}
}
开发者ID:cnicolov,项目名称:kit,代码行数:31,代码来源:client.go

示例2: MakeClientEndpoints

// MakeClientEndpoints returns an Endpoints struct where each endpoint invokes
// the corresponding method on the remote instance, via a transport/http.Client.
// Useful in a restsvc client.
func MakeClientEndpoints(instance string) (Endpoints, error) {
	if !strings.HasPrefix(instance, "http") {
		instance = "http://" + instance
	}
	tgt, err := url.Parse(instance)
	if err != nil {
		return Endpoints{}, err
	}
	tgt.Path = ""

	options := []httptransport.ClientOption{}

	// Note that the request encoders need to modify the request URL, changing
	// the path and method. That's fine: we simply need to provide specific
	// encoders for each endpoint.

	return Endpoints{
		PostConfigEndpoint:    httptransport.NewClient("POST", tgt, encodePostConfigRequest, decodePostConfigResponse, options...).Endpoint(),
		GetConfigEndpoint:     httptransport.NewClient("GET", tgt, encodeGetConfigRequest, decodeGetConfigResponse, options...).Endpoint(),
		PutConfigEndpoint:     httptransport.NewClient("PUT", tgt, encodePutConfigRequest, decodePutConfigResponse, options...).Endpoint(),
		PatchConfigEndpoint:   httptransport.NewClient("PATCH", tgt, encodePatchConfigRequest, decodePatchConfigResponse, options...).Endpoint(),
		DeleteConfigEndpoint:  httptransport.NewClient("DELETE", tgt, encodeDeleteConfigRequest, decodeDeleteConfigResponse, options...).Endpoint(),
		GetChannelsEndpoint:   httptransport.NewClient("GET", tgt, encodeGetChannelsRequest, decodeGetChannelsResponse, options...).Endpoint(),
		GetChannelEndpoint:    httptransport.NewClient("GET", tgt, encodeGetChannelRequest, decodeGetChannelResponse, options...).Endpoint(),
		PostChannelEndpoint:   httptransport.NewClient("POST", tgt, encodePostChannelRequest, decodePostChannelResponse, options...).Endpoint(),
		DeleteChannelEndpoint: httptransport.NewClient("DELETE", tgt, encodeDeleteChannelRequest, decodeDeleteChannelResponse, options...).Endpoint(),
		GetNotesEndpoint:      httptransport.NewClient("GET", tgt, encodeGetNotesRequest, decodeGetNotesResponse, options...).Endpoint(),
	}, nil
}
开发者ID:patterns,项目名称:re,代码行数:32,代码来源:endpoints.go

示例3: New

// New returns an AddService backed by an HTTP server living at the remote
// instance. We expect instance to come from a service discovery system, so
// likely of the form "host:port".
func New(instance string, tracer stdopentracing.Tracer, logger log.Logger) (addsvc.Service, error) {
	if !strings.HasPrefix(instance, "http") {
		instance = "http://" + instance
	}
	u, err := url.Parse(instance)
	if err != nil {
		return nil, err
	}

	// We construct a single ratelimiter middleware, to limit the total outgoing
	// QPS from this client to all methods on the remote instance. We also
	// construct per-endpoint circuitbreaker middlewares to demonstrate how
	// that's done, although they could easily be combined into a single breaker
	// for the entire remote instance, too.

	limiter := ratelimit.NewTokenBucketLimiter(jujuratelimit.NewBucketWithRate(100, 100))

	var sumEndpoint endpoint.Endpoint
	{
		sumEndpoint = httptransport.NewClient(
			"POST",
			copyURL(u, "/sum"),
			addsvc.EncodeHTTPGenericRequest,
			addsvc.DecodeHTTPSumResponse,
			httptransport.SetClientBefore(opentracing.FromHTTPRequest(tracer, "Sum", logger)),
		).Endpoint()
		sumEndpoint = opentracing.TraceClient(tracer, "Sum")(sumEndpoint)
		sumEndpoint = limiter(sumEndpoint)
		sumEndpoint = circuitbreaker.Gobreaker(gobreaker.NewCircuitBreaker(gobreaker.Settings{
			Name:    "Sum",
			Timeout: 30 * time.Second,
		}))(sumEndpoint)
	}

	var concatEndpoint endpoint.Endpoint
	{
		concatEndpoint = httptransport.NewClient(
			"POST",
			copyURL(u, "/concat"),
			addsvc.EncodeHTTPGenericRequest,
			addsvc.DecodeHTTPConcatResponse,
			httptransport.SetClientBefore(opentracing.FromHTTPRequest(tracer, "Concat", logger)),
		).Endpoint()
		concatEndpoint = opentracing.TraceClient(tracer, "Concat")(concatEndpoint)
		concatEndpoint = limiter(concatEndpoint)
		sumEndpoint = circuitbreaker.Gobreaker(gobreaker.NewCircuitBreaker(gobreaker.Settings{
			Name:    "Concat",
			Timeout: 30 * time.Second,
		}))(sumEndpoint)
	}

	return addsvc.Endpoints{
		SumEndpoint:    sumEndpoint,
		ConcatEndpoint: concatEndpoint,
	}, nil
}
开发者ID:subodhchhabra,项目名称:kit,代码行数:59,代码来源:client.go

示例4: TestClientEndpointEncodeError

func TestClientEndpointEncodeError(t *testing.T) {
	var (
		sampleErr = errors.New("Oh no, an error")
		enc       = func(r *http.Request, request interface{}) error { return sampleErr }
		dec       = func(r *http.Response) (response interface{}, err error) { return nil, nil }
	)

	u := &url.URL{
		Scheme: "https",
		Host:   "localhost",
		Path:   "/does/not/matter",
	}

	c := httptransport.NewClient(
		"GET",
		u,
		enc,
		dec,
	)

	_, err := c.Endpoint()(context.Background(), nil)
	if err == nil {
		t.Fatal("err == nil")
	}

	e, ok := err.(httptransport.TransportError)
	if !ok {
		t.Fatal("err is not of type github.com/go-kit/kit/transport/http.Err")
	}

	if want, have := sampleErr, e.Err; want != have {
		t.Fatalf("want %v, have %v", want, have)
	}
}
开发者ID:qband,项目名称:down,代码行数:34,代码来源:err_test.go

示例5: stringsvcFactory

func stringsvcFactory(ctx context.Context, method, path string) sd.Factory {
	return func(instance string) (endpoint.Endpoint, io.Closer, error) {
		if !strings.HasPrefix(instance, "http") {
			instance = "http://" + instance
		}
		tgt, err := url.Parse(instance)
		if err != nil {
			return nil, nil, err
		}
		tgt.Path = path

		// Since stringsvc doesn't have any kind of package we can import, or
		// any formal spec, we are forced to just assert where the endpoints
		// live, and write our own code to encode and decode requests and
		// responses. Ideally, if you write the service, you will want to
		// provide stronger guarantees to your clients.

		var (
			enc httptransport.EncodeRequestFunc
			dec httptransport.DecodeResponseFunc
		)
		switch path {
		case "/uppercase":
			enc, dec = encodeJSONRequest, decodeUppercaseResponse
		case "/count":
			enc, dec = encodeJSONRequest, decodeCountResponse
		default:
			return nil, nil, fmt.Errorf("unknown stringsvc path %q", path)
		}

		return httptransport.NewClient(method, tgt, enc, dec).Endpoint(), nil, nil
	}
}
开发者ID:crezam,项目名称:kit,代码行数:33,代码来源:main.go

示例6: newSetVerbosityEndpoint

func newSetVerbosityEndpoint(URL url.URL, path string) endpoint.Endpoint {
	URL.Path = path
	URL.RawPath = path

	newEndpoint := httptransport.NewClient(
		"POST",
		&URL,
		setVerbosityEncoder,
		setVerbosityDecoder,
	).Endpoint()

	return newEndpoint
}
开发者ID:xh3b4sd,项目名称:anna,代码行数:13,代码来源:endpoint.go

示例7: newResetLevelsEndpoint

func newResetLevelsEndpoint(URL url.URL, path string) endpoint.Endpoint {
	URL.Path = path
	URL.RawPath = path

	newEndpoint := httptransport.NewClient(
		"POST",
		&URL,
		resetLevelsEncoder,
		resetLevelsDecoder,
	).Endpoint()

	return newEndpoint
}
开发者ID:xh3b4sd,项目名称:anna,代码行数:13,代码来源:endpoint.go

示例8: makeFetchRoutesEndpoint

func makeFetchRoutesEndpoint(ctx context.Context, instance string) endpoint.Endpoint {
	u, err := url.Parse(instance)
	if err != nil {
		panic(err)
	}
	if u.Path == "" {
		u.Path = "/paths"
	}
	return kithttp.NewClient(
		"GET", u,
		encodeFetchRoutesRequest,
		decodeFetchRoutesResponse,
	).Endpoint()
}
开发者ID:crezam,项目名称:kit,代码行数:14,代码来源:proxying.go

示例9: httpFactory

func httpFactory(ctx context.Context, method, path string) loadbalancer.Factory {
	return func(instance string) (endpoint.Endpoint, io.Closer, error) {
		var e endpoint.Endpoint
		if !strings.HasPrefix(instance, "http") {
			instance = "http://" + instance
		}
		u, err := url.Parse(instance)
		if err != nil {
			return nil, nil, err
		}
		u.Path = path

		e = httptransport.NewClient(method, u, passEncode, passDecode).Endpoint()
		return e, nil, nil
	}
}
开发者ID:xiejianzheng,项目名称:goddd,代码行数:16,代码来源:main.go

示例10: SumEndpointFactory

// SumEndpointFactory transforms a http url into an Endpoint.
// The path of the url is reset to /sum.
func SumEndpointFactory(instance string) (endpoint.Endpoint, io.Closer, error) {
	sumURL, err := url.Parse(instance)
	if err != nil {
		return nil, nil, err
	}
	sumURL.Path = "/sum"

	client := httptransport.NewClient(
		"GET",
		sumURL,
		server.EncodeSumRequest,
		server.DecodeSumResponse,
		httptransport.SetClient(nil),
	)

	return client.Endpoint(), nil, nil
}
开发者ID:qband,项目名称:down,代码行数:19,代码来源:factory.go

示例11: ConcatEndpointFactory

// ConcatEndpointFactory transforms a http url into an Endpoint.
// The path of the url is reset to /concat.
func ConcatEndpointFactory(instance string) (endpoint.Endpoint, io.Closer, error) {
	concatURL, err := url.Parse(instance)
	if err != nil {
		return nil, nil, err
	}
	concatURL.Path = "/concat"

	client := httptransport.NewClient(
		"GET",
		concatURL,
		server.EncodeConcatRequest,
		server.DecodeConcatResponse,
		httptransport.SetClient(nil),
	)

	return client.Endpoint(), nil, nil
}
开发者ID:qband,项目名称:down,代码行数:19,代码来源:factory.go

示例12: makeUppercaseProxy

func makeUppercaseProxy(ctx context.Context, instance string) endpoint.Endpoint {
	if !strings.HasPrefix(instance, "http") {
		instance = "http://" + instance
	}
	u, err := url.Parse(instance)
	if err != nil {
		panic(err)
	}
	if u.Path == "" {
		u.Path = "/uppercase"
	}
	return httptransport.NewClient(
		"GET",
		u,
		encodeRequest,
		decodeUppercaseResponse,
	).Endpoint()
}
开发者ID:ronincumi,项目名称:kit,代码行数:18,代码来源:proxying.go

示例13: TestHTTPClientBufferedStream

func TestHTTPClientBufferedStream(t *testing.T) {
	var (
		testbody = "testbody"
		encode   = func(context.Context, *http.Request, interface{}) error { return nil }
		decode   = func(_ context.Context, r *http.Response) (interface{}, error) {
			return TestResponse{r.Body, ""}, nil
		}
	)

	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		w.Write([]byte(testbody))
	}))

	client := httptransport.NewClient(
		"GET",
		mustParse(server.URL),
		encode,
		decode,
		httptransport.SetBufferedStream(true),
	)

	res, err := client.Endpoint()(context.Background(), struct{}{})
	if err != nil {
		t.Fatal(err)
	}

	// Check that the response was successfully decoded
	response, ok := res.(TestResponse)
	if !ok {
		t.Fatal("response should be TestResponse")
	}

	// Check that response body was NOT closed
	b := make([]byte, len(testbody))
	_, err = response.Body.Read(b)
	if want, have := io.EOF, err; have != want {
		t.Fatalf("want %q, have %q", want, have)
	}
	if want, have := testbody, string(b); want != have {
		t.Errorf("want %q, have %q", want, have)
	}
}
开发者ID:subodhchhabra,项目名称:kit,代码行数:43,代码来源:client_test.go

示例14: MakeConcatEndpointFactory

// MakeConcatEndpointFactory generates a Factory that transforms an http url
// into an Endpoint.
//
// The path of the url is reset to /concat.
func MakeConcatEndpointFactory(tracer opentracing.Tracer, tracingLogger log.Logger) loadbalancer.Factory {
	return func(instance string) (endpoint.Endpoint, io.Closer, error) {
		concatURL, err := url.Parse(instance)
		if err != nil {
			return nil, nil, err
		}
		concatURL.Path = "/concat"

		client := httptransport.NewClient(
			"GET",
			concatURL,
			server.EncodeConcatRequest,
			server.DecodeConcatResponse,
			httptransport.SetClient(nil),
			httptransport.SetClientBefore(kitot.ToHTTPRequest(tracer, tracingLogger)),
		)

		return client.Endpoint(), nil, nil
	}
}
开发者ID:xiejianzheng,项目名称:goddd,代码行数:24,代码来源:factory.go

示例15: TestHTTPClient

func TestHTTPClient(t *testing.T) {
	var (
		encode    = func(*http.Request, interface{}) error { return nil }
		decode    = func(*http.Response) (interface{}, error) { return struct{}{}, nil }
		headers   = make(chan string, 1)
		headerKey = "X-Foo"
		headerVal = "abcde"
	)

	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		headers <- r.Header.Get(headerKey)
		w.WriteHeader(http.StatusOK)
	}))

	client := httptransport.NewClient(
		"GET",
		mustParse(server.URL),
		encode,
		decode,
		httptransport.SetClientBefore(httptransport.SetRequestHeader(headerKey, headerVal)),
	)

	_, err := client.Endpoint()(context.Background(), struct{}{})
	if err != nil {
		t.Fatal(err)
	}

	var have string
	select {
	case have = <-headers:
	case <-time.After(time.Millisecond):
		t.Fatalf("timeout waiting for %s", headerKey)
	}
	if want := headerVal; want != have {
		t.Errorf("want %q, have %q", want, have)
	}
}
开发者ID:cnicolov,项目名称:kit,代码行数:37,代码来源:client_test.go


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