|
| 1 | +// |
| 2 | +// |
| 3 | +// Tencent is pleased to support the open source community by making tRPC available. |
| 4 | +// |
| 5 | +// Copyright (C) 2023 Tencent. |
| 6 | +// All rights reserved. |
| 7 | +// |
| 8 | +// If you have downloaded a copy of the tRPC source code from Tencent, |
| 9 | +// please note that tRPC source code is licensed under the Apache 2.0 License, |
| 10 | +// A copy of the Apache 2.0 License is included in this file. |
| 11 | +// |
| 12 | +// |
| 13 | + |
| 14 | +// Package main is the client main package for FastHTTP demo. |
| 15 | +package main |
| 16 | + |
| 17 | +import ( |
| 18 | + "context" |
| 19 | + |
| 20 | + "github.com/valyala/fasthttp" |
| 21 | + |
| 22 | + "trpc.group/trpc-go/trpc-go/client" |
| 23 | + "trpc.group/trpc-go/trpc-go/codec" |
| 24 | + thttp "trpc.group/trpc-go/trpc-go/http" |
| 25 | + "trpc.group/trpc-go/trpc-go/log" |
| 26 | +) |
| 27 | + |
| 28 | +func main() { |
| 29 | + callWithFastHTTPClientProxy() |
| 30 | + callWithFastHTTPClient() |
| 31 | +} |
| 32 | + |
| 33 | +func callWithFastHTTPClientProxy() { |
| 34 | + proxy := thttp.NewFastHTTPClientProxy( |
| 35 | + "trpc.app.server.fasthttp", |
| 36 | + client.WithCurrentSerializationType(codec.SerializationTypeNoop), |
| 37 | + client.WithTarget("ip://127.0.0.1:8080"), |
| 38 | + ) |
| 39 | + |
| 40 | + reqHead := &thttp.FastHTTPClientReqHeader{ |
| 41 | + Method: fasthttp.MethodPost, |
| 42 | + DecorateRequest: func(req *fasthttp.Request) *fasthttp.Request { |
| 43 | + req.Header.Set("hello", "proxy") |
| 44 | + return req |
| 45 | + }, |
| 46 | + } |
| 47 | + rspHead := &thttp.FastHTTPClientRspHeader{} |
| 48 | + req := &codec.Body{Data: []byte("Hello, FastHTTP proxy!")} |
| 49 | + rsp := &codec.Body{} |
| 50 | + |
| 51 | + if err := proxy.Post(context.Background(), "/v1/hello", req, rsp, |
| 52 | + client.WithReqHead(reqHead), |
| 53 | + client.WithRspHead(rspHead), |
| 54 | + ); err != nil { |
| 55 | + log.Warnf("FastHTTPClientProxy request failed: %v", err) |
| 56 | + return |
| 57 | + } |
| 58 | + log.Infof("FastHTTPClientProxy response: %q, reply header: %q", |
| 59 | + rsp.Data, rspHead.Response.Header.Peek("reply")) |
| 60 | +} |
| 61 | + |
| 62 | +func callWithFastHTTPClient() { |
| 63 | + fc := thttp.NewFastHTTPClient("trpc.app.server.fasthttp") |
| 64 | + |
| 65 | + req := fasthttp.AcquireRequest() |
| 66 | + rsp := fasthttp.AcquireResponse() |
| 67 | + defer fasthttp.ReleaseRequest(req) |
| 68 | + defer fasthttp.ReleaseResponse(rsp) |
| 69 | + |
| 70 | + req.Header.SetMethod(fasthttp.MethodGet) |
| 71 | + req.Header.Set("hello", "client") |
| 72 | + req.SetRequestURI("http://127.0.0.1:8080/v1/hello") |
| 73 | + |
| 74 | + if err := fc.Do(req, rsp); err != nil { |
| 75 | + log.Warnf("FastHTTPClient request failed: %v", err) |
| 76 | + return |
| 77 | + } |
| 78 | + log.Infof("FastHTTPClient response: %q, reply header: %q", |
| 79 | + rsp.Body(), rsp.Header.Peek("reply")) |
| 80 | +} |
0 commit comments