1. [feat] func UnmarshalRequestJsonBody 反序列化http json body 2. [feat] func PostJson 序列化json数据做http post

pull/2/head v0.15.3
q191201771 4 years ago
parent f88655e19f
commit 67d32aba74

@ -0,0 +1,42 @@
// Copyright 2020, Chef. All rights reserved.
// https://github.com/q191201771/naza
//
// Use of this source code is governed by a MIT-style license
// that can be found in the License file.
//
// Author: Chef (191201771@qq.com)
package nazahttp
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"github.com/q191201771/naza/pkg/nazajson"
)
var ErrParamMissing = errors.New("nazahttp: param missing")
// @param r http请求对象
// @param info 输出参数,用于接收反序列化之后的数据
// @param keyFieldList 可选参数可指定一个或多个json中必须存在的字段
func UnmarshalRequestJsonBody(r *http.Request, info interface{}, keyFieldList ...string) error {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return err
}
j, err := nazajson.New(body)
if err != nil {
return err
}
for _, kf := range keyFieldList {
if !j.Exist(kf) {
return ErrParamMissing
}
}
return json.Unmarshal(body, info)
}

@ -0,0 +1,30 @@
// Copyright 2020, Chef. All rights reserved.
// https://github.com/q191201771/naza
//
// Use of this source code is governed by a MIT-style license
// that can be found in the License file.
//
// Author: Chef (191201771@qq.com)
package nazahttp
import (
"bytes"
"encoding/json"
"net/http"
)
// @param url 地址
// @param info 需要序列化的结构体
// @param client 注意如果为nil则使用http.DefaultClient
func PostJson(url string, info interface{}, client *http.Client) (*http.Response, error) {
j, err := json.Marshal(info)
if err != nil {
return nil, err
}
b := bytes.NewBuffer(j)
if client == nil {
client = http.DefaultClient
}
return client.Post(url, "application/json", b)
}
Loading…
Cancel
Save