Skip to content

Commit

Permalink
PackHandler use defined
Browse files Browse the repository at this point in the history
  • Loading branch information
flyhope committed Jul 13, 2022
1 parent da35d34 commit 9fec771
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 6 deletions.
5 changes: 2 additions & 3 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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()))
Expand All @@ -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 {
Expand Down
8 changes: 6 additions & 2 deletions pack/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,9 @@ func (p *EncoderJson) Decode(body []byte, response *Response) error {
}

func (p *EncoderJson) ContentType() string {
return "application/application/json"
}
return "application/json"
}

func (p *EncoderJson) ShowProtocol() Protocol {
return ProtocolJson
}
5 changes: 4 additions & 1 deletion pack/msgpack.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -31,3 +31,6 @@ func (p *EncoderMsgpack) ContentType() string {
return "application/x-msgpack"
}

func (p *EncoderMsgpack) ShowProtocol() Protocol {
return ProtocolMsgpack
}
1 change: 1 addition & 0 deletions pack/pack.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ type Pack interface {
Encode(*Request) ([]byte, error)
ContentType() string
Decode([]byte, *Response) error
ShowProtocol() Protocol
}

// 根据协议获取编码、解码器
Expand Down

0 comments on commit 9fec771

Please sign in to comment.