gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/x509ca/http_util.go (about)

     1  package x509ca
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  	"net/http"
     7  	"net/url"
     8  	"strings"
     9  )
    10  
    11  const (
    12  	REQ_TYPE_STRING = 1
    13  	REQ_TYPE_FORM   = 2
    14  )
    15  
    16  var (
    17  	defaultCertServiceUrl = "http://47.94.130.29:8080/certtools/"
    18  )
    19  
    20  func httpPost(reqType int, mothod string, paramStr string, param url.Values) string {
    21  
    22  	// 1.创建一个客户端
    23  	client := http.Client{}
    24  	var response *http.Response
    25  	var err error
    26  	if reqType == REQ_TYPE_STRING {
    27  		// 2.添加参数,参数类型为io.Reader
    28  		//
    29  		// 3.创建一个请求,请求方式可以是GET,也可以是POST
    30  		response, err = client.Post(defaultCertServiceUrl+mothod, "application/x-www-form-urlencoded", strings.NewReader(paramStr))
    31  	} else {
    32  		// 2.添加参数,参数类型为url.Values
    33  		//param := url.Values{
    34  		//	"userName": []string{"admin"},
    35  		//	"passWord": []string{"1234"},
    36  		//}
    37  		// 3.创建一个POST请求
    38  		response, err = client.PostForm(defaultCertServiceUrl+mothod, param)
    39  	}
    40  	catchError(err)
    41  	// 4.解析返回数据
    42  	if response.StatusCode != 200 {
    43  		fmt.Println("网络请求失败, StatusCode:", response.StatusCode)
    44  	}
    45  	// 5.读取后需要关闭response.Body
    46  	defer func() {
    47  		response.Body.Close()
    48  	}()
    49  	// 6.读取response.Body
    50  	body, err := ioutil.ReadAll(response.Body)
    51  	catchError(err)
    52  	//fmt.Println("请求结果:  " + string(body))
    53  	return string(body)
    54  }
    55  
    56  // 捕获错误
    57  func catchError(err error) {
    58  	// 使用延迟函数捕获错误
    59  	defer func() {
    60  		if er := recover(); er != nil {
    61  			fmt.Println(fmt.Sprintf("系统崩溃:%v", er))
    62  		}
    63  	}()
    64  	// 抛出错误
    65  	if err != nil {
    66  		panic(err)
    67  	}
    68  }