github.com/sandwich-go/boost@v1.3.29/httputil/client_imp.go (about)

     1  package httputil
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"io/ioutil"
     7  	"net/http"
     8  )
     9  
    10  // A Client is an HTTP client.
    11  // It wraps net/http's client and add some methods for making HTTP request easier.
    12  type httpClient struct {
    13  	*http.Client
    14  }
    15  
    16  // New create new an HTTP client.
    17  func New(c *http.Client) Client { return &httpClient{Client: c} }
    18  
    19  func (c *httpClient) err(resp *http.Response, message string) error {
    20  	if message == "" {
    21  		message = fmt.Sprintf("Get %s -> %d", resp.Request.URL.String(), resp.StatusCode)
    22  	}
    23  	return &Error{
    24  		Message:    message,
    25  		StatusCode: resp.StatusCode,
    26  		URL:        resp.Request.URL.String(),
    27  	}
    28  }
    29  
    30  func (c *httpClient) Bytes(url string) ([]byte, error) {
    31  	resp, err := c.Get(url)
    32  	if err != nil {
    33  		return nil, err
    34  	}
    35  	defer func() {
    36  		_ = resp.Body.Close()
    37  	}()
    38  	if resp.StatusCode != http.StatusOK {
    39  		return nil, c.err(resp, "")
    40  	}
    41  	return ioutil.ReadAll(resp.Body)
    42  }
    43  
    44  func (c *httpClient) String(url string) (string, error) {
    45  	bytes, err := c.Bytes(url)
    46  	if err != nil {
    47  		return "", err
    48  	}
    49  	return string(bytes), nil
    50  }
    51  
    52  func (c *httpClient) JSON(url string, v interface{}) error {
    53  	resp, err := c.Get(url)
    54  	if err != nil {
    55  		return err
    56  	}
    57  	defer func() {
    58  		_ = resp.Body.Close()
    59  	}()
    60  	if resp.StatusCode != http.StatusOK {
    61  		return c.err(resp, "")
    62  	}
    63  	err = json.NewDecoder(resp.Body).Decode(v)
    64  	if _, ok := err.(*json.SyntaxError); ok {
    65  		err = c.err(resp, "JSON syntax error at "+url)
    66  	}
    67  	return err
    68  }