Skip to content

Commit

Permalink
♻️ Refactoring code. hold refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
crossoverJie committed Nov 20, 2021
1 parent f16ad6a commit fe76b9d
Show file tree
Hide file tree
Showing 13 changed files with 455 additions and 170 deletions.
38 changes: 38 additions & 0 deletions client/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package client

import (
"github.com/crossoverJie/ptg/meta"
"net/http"
"time"
)

type (
Client interface {
Request() (*meta.Response, error)
}
)

const (
Http = "http"
Grpc = "grpc"
)

func NewClient(method, url, requestBody string, meta *meta.Meta) Client {
if meta.Protocol() == Http {
return &httpClient{
Method: method,
Url: url,
RequestBody: requestBody,
httpClient: &http.Client{
Transport: &http.Transport{
ResponseHeaderTimeout: time.Millisecond * time.Duration(1000),
DisableKeepAlives: true,
},
},
meta: meta,
}
} else {
return NewGrpcClient(meta)
}

}
62 changes: 34 additions & 28 deletions grpc_client.go → client/grpc_client.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
package main
package client

import (
"context"
"errors"
"fmt"
"github.com/crossoverJie/ptg/meta"
"github.com/golang/protobuf/jsonpb"
"github.com/jhump/protoreflect/desc"
"github.com/jhump/protoreflect/desc/protoparse"
"github.com/jhump/protoreflect/dynamic"
"github.com/jhump/protoreflect/dynamic/grpcdynamic"
"github.com/pkg/errors"
"google.golang.org/grpc"
"path/filepath"
"strings"
Expand All @@ -27,32 +28,35 @@ type grpcClient struct {
stub grpcdynamic.Stub
mtd *desc.MethodDescriptor
message []*dynamic.Message
meta *meta.Meta
}

func NewGrpcClient() Client {
func NewGrpcClient(meta *meta.Meta) Client {
one.Do(func() {
if client == nil {
var (
opts []grpc.DialOption
importPath []string
)

client = &grpcClient{}
client = &grpcClient{
meta: meta,
}
opts = append(opts, grpc.WithInsecure())
conn, err := grpc.DialContext(context.Background(), target, opts...)
conn, err := grpc.DialContext(context.Background(), meta.Target(), opts...)
if err != nil {
panic(fmt.Sprintf("create grpc connection err %v", err))
}
client.stub = grpcdynamic.NewStub(conn)

dir := filepath.Dir(protocolFile)
dir := filepath.Dir(meta.ProtocolFile())
importPath = append(importPath, dir)
client.mtd, err = GetMethodDescFromProto(fqn, protocolFile, importPath)
client.mtd, err = GetMethodDescFromProto(meta.Fqn(), meta.ProtocolFile(), importPath)
if err != nil {
panic(fmt.Sprintf("create grpc MethodDescriptor err %v", err))
}

client.message, err = getDataForCall(client.mtd)
client.message, err = client.getDataForCall()
if err != nil {
panic(fmt.Sprintf("create grpc message err %v", err))
}
Expand All @@ -62,22 +66,40 @@ func NewGrpcClient() Client {
return client
}

func (g *grpcClient) Request() (*Response, error) {
func (g *grpcClient) Request() (*meta.Response, error) {
//fmt.Printf("%p \n", &*g)\
start := time.Now()
rpc, err := g.stub.InvokeRpc(context.Background(), g.mtd, g.message[0])
r := &Response{
r := &meta.Response{
RequestTime: time.Since(start),
}
SlowRequestTime = r.slowRequest()
FastRequestTime = r.fastRequest()
//SlowRequestTime = r.slowRequest()
//FastRequestTime = r.fastRequest()
meta.GetResult().SetSlowRequestTime(r.SlowRequest()).
SetFastRequestTime(r.FastRequest())
if err != nil {
return nil, err
}
r.ResponseSize = len(rpc.String())
return r, nil
}

func (g *grpcClient) getDataForCall() ([]*dynamic.Message, error) {
var inputs []*dynamic.Message
var err error
if inputs, err = getPayloadMessages([]byte(g.meta.Body()), g.mtd); err != nil {
return nil, err
}

if len(inputs) > 0 {
unaryInput := inputs[0]

return []*dynamic.Message{unaryInput}, nil
}

return inputs, nil
}

func GetMethodDescFromProto(call, proto string, imports []string) (*desc.MethodDescriptor, error) {
p := &protoparse.Parser{ImportPaths: imports}

Expand Down Expand Up @@ -164,22 +186,6 @@ func findServiceSymbol(resolved map[string]*desc.FileDescriptor, fullyQualifiedN
return nil, fmt.Errorf("cannot find service %q", fullyQualifiedName)
}

func getDataForCall(mtd *desc.MethodDescriptor) ([]*dynamic.Message, error) {
var inputs []*dynamic.Message
var err error
if inputs, err = getPayloadMessages([]byte(body), mtd); err != nil {
return nil, err
}

if len(inputs) > 0 {
unaryInput := inputs[0]

return []*dynamic.Message{unaryInput}, nil
}

return inputs, nil
}

func getPayloadMessages(inputData []byte, mtd *desc.MethodDescriptor) ([]*dynamic.Message, error) {
var inputs []*dynamic.Message
data := inputData
Expand Down
71 changes: 16 additions & 55 deletions client.go → client/http_client.go
Original file line number Diff line number Diff line change
@@ -1,53 +1,25 @@
package main
package client

import (
"errors"
"fmt"
"github.com/crossoverJie/ptg/meta"
"github.com/pkg/errors"
"io"
"io/ioutil"
"net/http"
"strings"
"time"
)

type (
Client interface {
Request() (*Response, error)
}

httpClient struct {
Method string
Url string
RequestBody string
httpClient *http.Client
}

Response struct {
RequestTime time.Duration
ResponseSize int
}
)

func NewClient(method, url, requestBody string) Client {
if protocol == Http {
return &httpClient{
Method: method,
Url: url,
RequestBody: requestBody,
httpClient: &http.Client{
Transport: &http.Transport{
ResponseHeaderTimeout: time.Millisecond * time.Duration(1000),
DisableKeepAlives: true,
},
},
}
} else {
return NewGrpcClient()
}

type httpClient struct {
Method string
Url string
RequestBody string
httpClient *http.Client
meta *meta.Meta
}

func (c *httpClient) Request() (*Response, error) {
func (c *httpClient) Request() (*meta.Response, error) {
var payload io.Reader
if len(c.RequestBody) > 0 {
payload = strings.NewReader(`{"name":"abc"}`)
Expand All @@ -59,7 +31,7 @@ func (c *httpClient) Request() (*Response, error) {
return nil, err
}
req.Header.Add("User-Agent", "ptg")
for k, v := range headerMap {
for k, v := range c.meta.HeaderMap() {
req.Header.Add(k, v)
}

Expand All @@ -72,11 +44,13 @@ func (c *httpClient) Request() (*Response, error) {

start := time.Now()
response, err := c.httpClient.Do(req)
r := &Response{
r := &meta.Response{
RequestTime: time.Since(start),
}
SlowRequestTime = r.slowRequest()
FastRequestTime = r.fastRequest()
//SlowRequestTime = r.slowRequest()
//FastRequestTime = r.fastRequest()
meta.GetResult().SetSlowRequestTime(r.SlowRequest()).
SetFastRequestTime(r.FastRequest())
if err != nil {
return nil, err
}
Expand All @@ -100,16 +74,3 @@ func (c *httpClient) Request() (*Response, error) {
r.ResponseSize = len(body)
return r, nil
}

func (r *Response) fastRequest() time.Duration {
if r.RequestTime < FastRequestTime {
return r.RequestTime
}
return FastRequestTime
}
func (r *Response) slowRequest() time.Duration {
if r.RequestTime > SlowRequestTime {
return r.RequestTime
}
return SlowRequestTime
}
19 changes: 8 additions & 11 deletions client_test.go → client/http_client_test.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,18 @@
package main
package client

import (
"fmt"
"github.com/crossoverJie/ptg/meta"
"github.com/docker/go-units"
"testing"
)

func Test_client_Request(t *testing.T) {
httpClient := NewClient("GET", "http://gobyexample.com", "")
request, err := httpClient.Request()
if err != nil {
fmt.Println(err)
}
fmt.Println(request)
}
func Test_client_Request2(t *testing.T) {
httpClient := NewClient("POST", "http://localhost:8080/post", `{"name":"abc"}`)
func Test_httpClient_Request(t *testing.T) {
meta.NewResult()
httpClient := NewClient("GET",
"http://gobyexample.com", "",
meta.NewMeta("http://gobyexample.com", "GET", "", "", Http, "",
"", 1, 1, nil, nil))
request, err := httpClient.Request()
if err != nil {
fmt.Println(err)
Expand Down
Loading

0 comments on commit fe76b9d

Please sign in to comment.