fix json marshal in http request

This commit is contained in:
sunxingbo 2021-07-20 22:38:37 +08:00
parent 12af439a9c
commit 4a85237faf
3 changed files with 31 additions and 1 deletions

View File

@ -258,6 +258,12 @@ func (b *BeegoHTTPRequest) AddFilters(fcs ...FilterChain) *BeegoHTTPRequest {
return b
}
// SetEscapeHTML is used to set the flag whether escape HTML special characters during processing
func (b *BeegoHTTPRequest) SetEscapeHTML(isEscape bool) *BeegoHTTPRequest {
b.setting.EscapeHTML = isEscape
return b
}
// Param adds query param in to request.
// params build query string as ?key1=value1&key2=value2...
func (b *BeegoHTTPRequest) Param(key, value string) *BeegoHTTPRequest {
@ -334,7 +340,7 @@ func (b *BeegoHTTPRequest) YAMLBody(obj interface{}) (*BeegoHTTPRequest, error)
// JSONBody adds the request raw body encoded in JSON.
func (b *BeegoHTTPRequest) JSONBody(obj interface{}) (*BeegoHTTPRequest, error) {
if b.req.Body == nil && obj != nil {
byts, err := json.Marshal(obj)
byts, err := b.Marshal(obj)
if err != nil {
return b, berror.Wrap(err, InvalidJSONBody, "obj could not be converted to JSON body")
}
@ -345,6 +351,17 @@ func (b *BeegoHTTPRequest) JSONBody(obj interface{}) (*BeegoHTTPRequest, error)
return b, nil
}
func (b *BeegoHTTPRequest) Marshal(obj interface{}) ([]byte, error) {
bf := bytes.NewBuffer([]byte{})
jsonEncoder := json.NewEncoder(bf)
jsonEncoder.SetEscapeHTML(b.setting.EscapeHTML)
err := jsonEncoder.Encode(obj)
if err != nil {
return nil, err
}
return bf.Bytes(), nil
}
func (b *BeegoHTTPRequest) buildURL(paramBody string) {
// build GET url with query string
if b.req.Method == "GET" && len(paramBody) > 0 {

View File

@ -18,6 +18,7 @@ import (
"bytes"
"context"
"errors"
"fmt"
"io/ioutil"
"net"
"net/http"
@ -435,3 +436,13 @@ func TestBeegoHTTPRequestXMLBody(t *testing.T) {
// TODO
func TestBeegoHTTPRequestResponseForValue(t *testing.T) {
}
func TestBeegoHTTPRequestMarshal(t *testing.T) {
req := Post("http://beego.me")
req.SetEscapeHTML(false)
body := map[string]interface{} {
"escape": "left&right",
}
b, _ := req.Marshal(body)
assert.Equal(t,fmt.Sprintf(`{"escape":"left&right"}%s`, "\n"), string(b))
}

View File

@ -37,6 +37,7 @@ type BeegoHTTPSettings struct {
Retries int // if set to -1 means will retry forever
RetryDelay time.Duration
FilterChains []FilterChain
EscapeHTML bool // if set to false means will not escape escape HTML special characters during processing, default true
}
// createDefaultCookie creates a global cookiejar to store cookies.
@ -66,6 +67,7 @@ var defaultSetting = BeegoHTTPSettings{
ReadWriteTimeout: 60 * time.Second,
Gzip: true,
FilterChains: make([]FilterChain, 0, 4),
EscapeHTML: true,
}
var (