package httpreq

import (
	"io"
	"net"
	"net/http"
	"time"
)

const (
	defaultTimeout = 10 * time.Second
)

type Response struct {
	StatusCode int
	Header     http.Header
	Body       []byte
}

func Send(req *http.Request, timeout time.Duration) (_ Response, err error) {
	if timeout == 0 {
		timeout = defaultTimeout
	}
	var netClient = &http.Client{
		Timeout: timeout,
	}

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

	buf, err := io.ReadAll(resp.Body)
	if err != nil {
		return
	}
	resp.Body.Close()

	return Response{
		StatusCode: resp.StatusCode,
		Body:       buf,
		Header:     resp.Header,
	}, nil
}

func IsTimeoutError(err error) bool {
	e, ok := err.(net.Error)
	if !ok {
		return false
	}
	if e.Timeout() {
		return true
	}
	return false
}
