初始版本
This commit is contained in:
60
httpx/httpx.go
Normal file
60
httpx/httpx.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
HTTP *http.Client
|
||||
}
|
||||
|
||||
func New(timeout time.Duration) *Client {
|
||||
return &Client{HTTP: &http.Client{Timeout: timeout}}
|
||||
}
|
||||
|
||||
func Wrap(client *http.Client) *Client {
|
||||
if client == nil {
|
||||
client = http.DefaultClient
|
||||
}
|
||||
return &Client{HTTP: client}
|
||||
}
|
||||
|
||||
func (c *Client) GetBytes(target string) ([]byte, int, error) {
|
||||
resp, err := c.HTTP.Get(target)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
return body, resp.StatusCode, err
|
||||
}
|
||||
|
||||
func (c *Client) PostJSON(target string, data any) ([]byte, int, error) {
|
||||
body, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
resp, err := c.HTTP.Post(target, "application/json", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
respBody, err := io.ReadAll(resp.Body)
|
||||
return respBody, resp.StatusCode, err
|
||||
}
|
||||
|
||||
func MustOK(body []byte, status int, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if status >= http.StatusMultipleChoices {
|
||||
return fmt.Errorf("http status=%d body=%s", status, strings.TrimSpace(string(body)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user