github.com/searKing/golang/go@v1.2.117/net/restful/client.go (about)

     1  // Copyright 2020 The searKing Author. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package restful
     6  
     7  import (
     8  	"errors"
     9  	"io"
    10  	"io/ioutil"
    11  	"net/http"
    12  	"strings"
    13  	"time"
    14  )
    15  
    16  const timeout = 4 * time.Second
    17  
    18  var defaultClient = &http.Client{
    19  	Timeout: timeout,
    20  }
    21  
    22  func httpRequest(method string, url string, body io.Reader) (*http.Request, error) {
    23  	return http.NewRequest(method, url, body)
    24  }
    25  
    26  func httpMethod(req *http.Request) (string, error) {
    27  	resp, err := defaultClient.Do(req)
    28  	if err != nil {
    29  		return "", err
    30  	}
    31  	defer resp.Body.Close()
    32  	body, err := ioutil.ReadAll(resp.Body)
    33  	if err != nil {
    34  		return "", err
    35  	}
    36  	if resp.StatusCode >= 300 {
    37  		return "", errors.New(string(body))
    38  	}
    39  	return string(body), nil
    40  }
    41  
    42  func Get(url string) (string, error) {
    43  	req, err := httpRequest(http.MethodGet, url, nil)
    44  	if err != nil {
    45  		return "", err
    46  	}
    47  	return httpMethod(req)
    48  }
    49  
    50  func Post(url string, body []byte) (string, error) {
    51  	req, err := httpRequest(http.MethodPost, url, strings.NewReader(string(body)))
    52  	if err != nil {
    53  		return "", err
    54  	}
    55  	req.Header.Set("Content-Type", "application/json")
    56  	return httpMethod(req)
    57  }
    58  
    59  func Put(url string, body []byte) (string, error) {
    60  	req, err := httpRequest(http.MethodPut, url, strings.NewReader(string(body)))
    61  	if err != nil {
    62  		return "", err
    63  	}
    64  	req.Header.Set("Content-Type", "application/json")
    65  	return httpMethod(req)
    66  }