Example #1
0
func httpPostJSON(clt *http.Client, url string, body []byte, response interface{}) error {
	api.DebugPrintPostJSONRequest(url, body)
	httpResp, err := clt.Post(url, "application/json; charset=utf-8", bytes.NewReader(body))
	if err != nil {
		return err
	}
	defer httpResp.Body.Close()

	if httpResp.StatusCode != http.StatusOK {
		return fmt.Errorf("http.Status: %s", httpResp.Status)
	}
	return api.DecodeJSONHttpResponse(httpResp.Body, response)
}
Example #2
0
func httpDownloadToWriter(clt *http.Client, url string, body []byte, buf []byte, writer io.Writer, errorResult *core.Error) (written int64, err error) {
	api.DebugPrintPostJSONRequest(url, body)
	httpResp, err := clt.Post(url, "application/json; charset=utf-8", bytes.NewReader(body))
	if err != nil {
		return 0, err
	}
	defer httpResp.Body.Close()

	if httpResp.StatusCode != http.StatusOK {
		return 0, fmt.Errorf("http.Status: %s", httpResp.Status)
	}

	buf2 := buf // 保存预先读取的少量头部信息
	switch n, err := io.ReadFull(httpResp.Body, buf2); err {
	case nil:
		break
	case io.ErrUnexpectedEOF:
		buf2 = buf2[:n]
		break
	case io.EOF: // 基本不会出现
		return 0, nil
	default:
		return 0, err
	}

	var httpRespBody io.Reader
	if len(buf2) < len(buf) {
		httpRespBody = bytes.NewReader(buf2)
	} else {
		httpRespBody = io.MultiReader(bytes.NewReader(buf2), httpResp.Body)
	}

	buf3 := trimLeft(buf2)
	if bytes.HasPrefix(buf3, errRespBeginWithCode) || bytes.HasPrefix(buf3, errRespBeginWithMsg) {
		// 返回的是错误信息
		return 0, api.DecodeJSONHttpResponse(httpRespBody, errorResult)
	} else {
		// 返回的是媒体流
		return io.Copy(writer, httpRespBody)
	}
}