2024-05-29 03:05:09 +00:00
|
|
|
package http
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-08-14 10:29:59 +00:00
|
|
|
"errors"
|
2024-05-29 03:05:09 +00:00
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/1Panel-dev/1Panel/backend/global"
|
|
|
|
"github.com/1Panel-dev/1Panel/backend/utils/xpack"
|
|
|
|
)
|
|
|
|
|
2024-06-06 09:37:38 +00:00
|
|
|
func HandleGet(url, method string, timeout int) (int, []byte, error) {
|
2024-06-06 06:16:14 +00:00
|
|
|
transport := xpack.LoadRequestTransport()
|
2024-06-06 09:37:38 +00:00
|
|
|
return HandleGetWithTransport(url, method, transport, timeout)
|
2024-06-05 15:46:11 +00:00
|
|
|
}
|
|
|
|
|
2024-06-06 09:37:38 +00:00
|
|
|
func HandleGetWithTransport(url, method string, transport *http.Transport, timeout int) (int, []byte, error) {
|
2024-05-29 03:05:09 +00:00
|
|
|
defer func() {
|
|
|
|
if r := recover(); r != nil {
|
2024-06-06 03:18:12 +00:00
|
|
|
global.LOG.Errorf("handle request failed, error message: %v", r)
|
2024-05-29 03:05:09 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2024-06-06 09:37:38 +00:00
|
|
|
client := http.Client{Timeout: time.Duration(timeout) * time.Second, Transport: transport}
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
|
2024-05-29 03:05:09 +00:00
|
|
|
defer cancel()
|
|
|
|
request, err := http.NewRequestWithContext(ctx, method, url, nil)
|
|
|
|
if err != nil {
|
|
|
|
return 0, nil, err
|
|
|
|
}
|
|
|
|
request.Header.Set("Content-Type", "application/json")
|
|
|
|
resp, err := client.Do(request)
|
|
|
|
if err != nil {
|
|
|
|
return 0, nil, err
|
|
|
|
}
|
2024-08-14 10:29:59 +00:00
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
|
|
return 0, nil, errors.New(resp.Status)
|
|
|
|
}
|
2024-05-29 03:05:09 +00:00
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
|
|
|
return 0, nil, err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
return resp.StatusCode, body, nil
|
|
|
|
}
|