package webutils

import (
	"errors"
	"io"
	"net/http"
	"strings"
	"time"

	"github.com/sirupsen/logrus"
)

func Get(reqUrl string, timeout time.Duration) ([]byte, error) {
	req, err := http.NewRequest(http.MethodGet, reqUrl, nil)
	if err != nil {
		logrus.Error(err)
		return nil, err
	}

	cli := http.Client{
		Timeout: timeout,
	}

	resp, err := cli.Do(req)
	if err != nil {
		logrus.Error(err)
		return nil, err
	}

	defer resp.Body.Close()

	b, err := io.ReadAll(resp.Body)
	if err != nil {
		logrus.Error(err)
		return nil, err
	}

	return b, nil
}

func Post(reqUrl string, payload string, timeout time.Duration) ([]byte, error) {
	req, err := http.NewRequest(http.MethodPost, reqUrl, strings.NewReader(payload))
	if err != nil {
		logrus.Error(err)
		return nil, err
	}

	cli := http.Client{
		Timeout: timeout,
	}

	resp, err := cli.Do(req)
	if err != nil {
		logrus.Error(err)
		return nil, err
	}

	if resp.StatusCode != http.StatusOK {
		logrus.Error("状态码错误：", resp)
		return nil, errors.New("状态码错误")
	}

	defer resp.Body.Close()

	b, err := io.ReadAll(resp.Body)
	if err != nil {
		logrus.Error(err)
		return nil, err
	}

	return b, nil
}
