golang非标准http请求的坑

golang原生的Header方法和beego的header()有坑,如果header不是标准的格式,会自动转成标准的格式,例如X-REST-API-Key会变成X-Rest-Api-Key,因此需要使用req.Header来绕过这个坑


func HttpRunJavaCloudCode(appKey, restKey, functionName string, body map[string]interface{}) (res string, err error) {
	url := "http://www.test.com"
	bodyByte, err := json.Marshal(body)
	if err != nil {
		return "", errors.New(fmt.Sprintf("json :%+v: err:%s", body, err))
	}
	var req *http.Request
	if req, err = http.NewRequest("POST", url, bytes.NewReader(bodyByte)); err != nil {
		return "", err
	}
	req.Header["X-Application-Id"] = []string{appKey}
	req.Header["X-REST-API-Key"] = []string{restKey}
	req.Header.Set("Content-Type", "application/json")
	var httpRes *http.Response
	if httpRes, err = (&http.Client{
		Timeout: time.Second * time.Duration(connectTimeout),
	}).Do(req); err != nil {
		return "", err
	}
	if bodyByte, err = ioutil.ReadAll(httpRes.Body); err != nil {
		return "", err
	}
	res = string(bodyByte)

	return
}



你可能感兴趣的:(go)