Hanlen
11/15/2019 - 9:34 AM

http and https post

with timeout

func httpsPost(header map[string]string, bodyStr, _url string, timeout int) ([]byte, error) {
	bodyR := strings.NewReader(bodyStr)
	req, err := http.NewRequest("POST", _url, bodyR)
	if err != nil {
		//logger.Warnf("http.NewRequest failed, https err = %s", err.Error())
		return nil, err
	}

	if header != nil {
		for k, v := range header {
			req.Header.Add(k, v)
		}
	}

	// This transport is what's causing unclosed connections.
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	hc := &http.Client{Timeout: time.Duration(timeout) * time.Second, Transport: tr}

	resp, err := hc.Do(req)
	if err != nil {
		//logger.Warnf("ReportTasks task failed, https err = %s", err.Error())
		return nil, err
	}
	defer resp.Body.Close()
	respStr, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		//logger.Warnf("ReportTasks get resp body failed, err = %s", err.Error())
		return nil, err
	}

	return respStr, nil
}

func httpPost(header map[string]string, bodyStr, _url string, timeout int) ([]byte, error) {
	var err error
	var resp *http.Response

	if header == nil {
		resp, err = http.Post(_url, "text/plain", strings.NewReader(bodyStr))
	} else {
		var reqst *http.Request
		reqst, err = http.NewRequest("POST", _url, strings.NewReader(bodyStr))
		if err != nil {
			return nil, err
		}
		for k, v := range header {
			reqst.Header.Add(k, v)
		}
		client := &http.Client{Timeout: time.Duration(timeout) * time.Second}
		resp, err = client.Do(reqst)
	}

	if err != nil {
		// logger.Warnf("ReportTasks failed")
		return nil, err
	} else if resp.StatusCode != 200 {
		err = errors.Errorf("ReportTasks task failed, status code = %d", resp.StatusCode)
	}
	defer resp.Body.Close()

	respStr, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// logger.Warnf("ReportTasks get resp body failed, err = %s", err.Error())
		return nil, err
	}

	return respStr, nil
}

func HttpPost(header map[string]string, bodyStr, _url string, timeout int) ([]byte, error) {
	if timeout == 0 {
		timeout = 10
	}

	if strings.HasPrefix(_url, "https://") {
		return httpsPost(header, bodyStr, _url, timeout)
	} else {
		return httpPost(header, bodyStr, _url, timeout)
	}
}