package util

import (
	"DataShare/global"
	"bytes"
	"fmt"
	"github.com/sirupsen/logrus"
	"io/ioutil"
	"net/http"
	"time"
)

func HttpPost(url string, bytesData []byte,xftoken string) ([]byte, error) {

	reader := bytes.NewReader(bytesData)
	request, err := http.NewRequest("POST", url, reader)
	if err != nil {
		fmt.Println(err.Error())
		msg := fmt.Sprintf("new request failed,request url:%s, param:%s  errmsg:%s",url,string(bytesData),err.Error())
		global.SystemLogger.Log(logrus.ErrorLevel,msg)
		return nil,err
	}
	//request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	request.Header.Set("Content-Type", "application/json")
	request.Header.Set("xftoken",xftoken)
	client := http.Client{
		Timeout: time.Duration(60 * time.Second),
	}
	resp, err := client.Do(request)
	if err != nil {
		msg := fmt.Sprintf("client.Do failed,request url:%s, param:%s errmsg:%s",url,string(bytesData),err.Error())
		global.SystemLogger.Log(logrus.ErrorLevel,msg)
		return nil,err
	}
	defer resp.Body.Close()
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err.Error())
		msg := fmt.Sprintf("ioutil readall failed,request url:%s, param:%s errmsg:%s",url,string(bytesData),err.Error())
		global.SystemLogger.Log(logrus.ErrorLevel,msg)
		return nil,err
	}

	return respBytes,err
}
