From bf6b0d3e1ff4275d7ec325ffb27ecd855315886f Mon Sep 17 00:00:00 2001 From: Hubery Date: Fri, 6 Mar 2015 14:12:24 +0800 Subject: [PATCH] add JsonBody --- httplib/httplib.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/httplib/httplib.go b/httplib/httplib.go index 7ff2f1d2..bd8bc776 100644 --- a/httplib/httplib.go +++ b/httplib/httplib.go @@ -253,6 +253,22 @@ func (b *BeegoHttpRequest) Body(data interface{}) *BeegoHttpRequest { return b } + +// JsonBody adds request raw body encoding by JSON. +func (b *BeegoHttpRequest) JsonBody(obj interface{}) (*BeegoHttpRequest, error) { + if b.req.Body == nil && obj != nil { + buf := bytes.NewBuffer(nil) + enc := json.NewEncoder(buf) + if err := enc.Encode(obj); err != nil { + return b, err + } + b.req.Body = ioutil.NopCloser(buf) + b.req.ContentLength = int64(buf.Len()) + b.req.Header.Set("Content-Type", "application/json") + } + return b, nil +} + func (b *BeegoHttpRequest) buildUrl(paramBody string) { // build GET url with query string if b.req.Method == "GET" && len(paramBody) > 0 {