package models

import (
	"bytes"
	"io/ioutil"
	"net/http"
	"strings"
)

type XyzRequest struct {
}

// Get请求 url里携带参数
func (class *XyzRequest) GetSend(url string) (string, error) {
	var err error
	resp, err1 := http.Get(url)
	if err1 != nil {
		return "", err
	}
	defer resp.Body.Close()
	body, err2 := ioutil.ReadAll(resp.Body)
	if err2 != nil {
		return "", err
	}
	return string(body), nil

}

// post地址 请求参数，string格式
func (class *XyzRequest) PostSend(url string, KVstring string) (string, error) {
	var err error
	resp, err1 := http.Post(url, "application/x-www-form-urlencoded", strings.NewReader(KVstring))
	if err1 != nil {
		return "", err
	}
	defer resp.Body.Close()
	body, err2 := ioutil.ReadAll(resp.Body)
	if err2 != nil {
		return "", err
	}
	return string(body), nil
}

// post地址 请求参数，json格式 返回json
func (class *XyzRequest) PostJson(url string, strJson string) (string, error) {
	var err error
	req, _ := http.NewRequest("POST", url, bytes.NewBuffer([]byte(strJson)))
	req.Header.Set("Content-Type", "application/json; charset=UTF-8")
	client := &http.Client{}
	resp, err2 := client.Do(req)
	if err2 != nil {
		return "", err
	}
	defer resp.Body.Close()
	// fmt.Println("status", resp.Status)
	// fmt.Println("headers", resp.Header)
	body, err3 := ioutil.ReadAll(resp.Body)
	if err3 != nil {
		return "", err
	}
	return string(body), nil
}
