给定post请求包体(是json的字符串)

{

    "A" : 10086,

    "B" : "请求信息"

}

发送HTTP过程

1. 将post请求包体(是个json格式的字符串),Marshal成json格式

2. 发送HTTP请求

3. 接收HTTP返回体

4. 解析HTTP返回体,判断返回是否正确

// HTTP: post请求参数
// {
// 	"A" : 10086,
// 	"B" : "请求信息"
// }
type RequestParam struct {
	A int    `json:"A"`
	B string `json:"B"`
}

// HTTP返回Body
type HTTPRspBody struct {
	Result Results `json:"Result"`
}
type Results struct {
	RequestID     string   `json:"Result"`
	HasError      bool     `json:"HasError"`
	ResponseItems ErrorMsg `json:"ResponseItems"`
}
type ErrorMsg struct {
	ErrorMsg string `json:"ErrorMsg"`
}

// 修改供应商信息
func testPostHttp() error {

	var (
		err    error
		errMsg string
	)

	// json.Marshal
	reqParam, err := json.Marshal(&RequestParam{})
	if err != nil {
		log.Error("Marshal RequestParam fail, err:%v", err)
		return err
	}

	// 准备: HTTP请求
	reqBody := strings.NewReader(string(reqParam))
	httpReq, err := http.NewRequest("POST", url, reqBody)
	if err != nil {
		log.Error("NewRequest fail, url: %s, reqBody: %s, err: %v", url, reqBody, err)
		return err
	}
	httpReq.Header.Add("Content-Type", "application/json")

	// DO: HTTP请求
	httpRsp, err := http.DefaultClient.Do(httpReq)
	if err != nil {
		log.Error("do http fail, url: %s, reqBody: %s, err:%v", url, reqBody, err)
		return err
	}
	defer httpRsp.Body.Close()

	// Read: HTTP结果
	rspBody, err := ioutil.ReadAll(httpRsp.Body)
	if err != nil {
		log.Error("ReadAll failed, url: %s, reqBody: %s, err: %v", url, reqBody, err)
		return err
	}

	// unmarshal: 解析HTTP返回的结果
	// 		body: {"Result":{"RequestId":"12131","HasError":true,"ResponseItems":{"ErrorMsg":"错误信息"}}}
	var result HTTPRspBody
	if err = json.Unmarshal(rspBody, &result); err != nil {
		log.Error("Unmarshal fail, err:%v", err)
		return err
	}
	if result.Result.HasError {
		log.Error("http post fail, url: %s, reqBody: %s, ErrorMsg:%s", url, reqBody, result.Result.ResponseItems.ErrorMsg)
		return errors.New(result.Result.ResponseItems.ErrorMsg)
	}
	log.Debug("do post http success, url: %s, reqBody: %s, body: %s %s", url, reqBody, string(rspBody), errMsg)

	return nil
}