github.com/volts-dev/volts@v0.0.0-20240120094013-5e9c65924106/client/rpc_request.go (about) 1 package client 2 3 import ( 4 "io" 5 6 "github.com/volts-dev/volts/internal/body" 7 "github.com/volts-dev/volts/internal/header" 8 ) 9 10 type ( 11 rpcRequest struct { 12 service string //服务名 13 method string //method和endpoint目前是一样的是方法名 14 ContentLength int64 15 header header.Header 16 body *body.TBody 17 opts RequestOptions 18 } 19 ) 20 21 func newRpcRequest(service, method string, data interface{}, opts ...RequestOption) (*rpcRequest, error) { 22 reqOpts := RequestOptions{} 23 for _, o := range opts { 24 o(&reqOpts) 25 } 26 27 req := &rpcRequest{ 28 service: service, 29 method: method, 30 body: body.New(reqOpts.Codec), 31 ContentLength: 0, 32 opts: reqOpts, 33 } 34 35 err := req.write(data) 36 if err != nil { 37 return nil, err 38 } 39 return req, nil 40 } 41 42 // TODO 43 // 写入请求二进制数据 44 func (self *rpcRequest) write(data interface{}) error { 45 if data == nil { 46 return nil 47 } 48 var err error 49 50 switch v := data.(type) { 51 case io.Reader: 52 d, err := io.ReadAll(v) 53 if err != nil { 54 return err 55 } 56 _, err = self.body.Encode(d) 57 58 case []byte: 59 if self.opts.Encoded { 60 _, err = self.body.Data.Write(v) 61 } else { 62 _, err = self.body.Encode(v) 63 } 64 default: 65 _, err = self.body.Encode(v) 66 } 67 68 self.ContentLength = int64(self.body.Data.Len()) 69 return err 70 } 71 72 func (r *rpcRequest) Service() string { 73 return r.service 74 } 75 76 func (self *rpcRequest) Method() string { 77 return self.method 78 } 79 80 func (self *rpcRequest) ContentType() string { 81 return self.body.Codec.String() 82 } 83 84 func (self *rpcRequest) Body() *body.TBody { 85 return self.body 86 } 87 88 func (*rpcRequest) Stream() bool { 89 return false 90 } 91 func (self *rpcRequest) Header() header.Header { 92 if self.header == nil { 93 self.header = make(header.Header) 94 } 95 return self.header 96 }