From 9fec771fa89abc5feb6c156cbce541016b9dca54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E6=9E=A8=E7=85=8A?= Date: Wed, 13 Jul 2022 19:33:39 +0800 Subject: [PATCH] PackHandler use defined --- client.go | 5 ++--- pack/json.go | 8 ++++++-- pack/msgpack.go | 5 ++++- pack/pack.go | 1 + 4 files changed, 13 insertions(+), 6 deletions(-) diff --git a/client.go b/client.go index b97eff5..1abe534 100644 --- a/client.go +++ b/client.go @@ -62,7 +62,7 @@ func (c *Client) SetResponseRetStruct(retVal interface{}) *Client { // 开始发送请求数据 func (c *Client) Send() error { - if c.PackHandler == nil { + if c.PackHandler == nil || c.PackHandler.ShowProtocol() != c.Request.Protocol { c.PackHandler = pack.GetPackHandler(c.Request.Protocol) } data, err := c.PackHandler.Encode(c.Request) @@ -75,7 +75,6 @@ func (c *Client) Send() error { buffer := header.Bytes() buffer.Write(data) - c.Http.Body = ioutil.NopCloser(buffer) c.Http.Header.Set("Content-Type", c.PackHandler.ContentType()) c.Http.Header.Add("Content-Length", fmt.Sprintf("%d", buffer.Len())) @@ -90,7 +89,7 @@ func (c *Client) Send() error { // 解析处理 headerData := pack.NewHeaderWithBody(body, c.Request.Protocol) - if c.PackHandler == nil { + if c.PackHandler == nil || c.PackHandler.ShowProtocol() != headerData.Packager { c.PackHandler = pack.GetPackHandler(headerData.Packager) } if c.PackHandler == nil { diff --git a/pack/json.go b/pack/json.go index a037189..a761eac 100644 --- a/pack/json.go +++ b/pack/json.go @@ -18,5 +18,9 @@ func (p *EncoderJson) Decode(body []byte, response *Response) error { } func (p *EncoderJson) ContentType() string { - return "application/application/json" -} \ No newline at end of file + return "application/json" +} + +func (p *EncoderJson) ShowProtocol() Protocol { + return ProtocolJson +} diff --git a/pack/msgpack.go b/pack/msgpack.go index a6974c5..2f5cb78 100644 --- a/pack/msgpack.go +++ b/pack/msgpack.go @@ -20,7 +20,7 @@ func (p *EncoderMsgpack) Encode(request *Request) ([]byte, error) { return buf.Bytes(), err } -func (p *EncoderMsgpack) Decode(body []byte, response *Response) error{ +func (p *EncoderMsgpack) Decode(body []byte, response *Response) error { reader := bytes.NewReader(body) decoder := msgpack.NewDecoder(reader) decoder.UseJSONTag(true) @@ -31,3 +31,6 @@ func (p *EncoderMsgpack) ContentType() string { return "application/x-msgpack" } +func (p *EncoderMsgpack) ShowProtocol() Protocol { + return ProtocolMsgpack +} diff --git a/pack/pack.go b/pack/pack.go index e254913..58be859 100644 --- a/pack/pack.go +++ b/pack/pack.go @@ -13,6 +13,7 @@ type Pack interface { Encode(*Request) ([]byte, error) ContentType() string Decode([]byte, *Response) error + ShowProtocol() Protocol } // 根据协议获取编码、解码器