增加请求发送以及响应体读取

This commit is contained in:
白茶清欢 2022-06-30 17:52:09 +08:00
parent 091571128e
commit 24fe4c9adc

27
rpc.go
View File

@ -8,8 +8,11 @@
package rpc
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"sync"
@ -261,12 +264,21 @@ func (r *request) Send(ctx *gin.Context, serviceFlag string, apiFlag string, par
err error
fullURL string
client *httpclient.HttpClient
body []byte
response *httpclient.Response
responseBody []byte
)
if serviceConfig, apiConfig, err = r.GetServiceApi(serviceFlag, apiFlag); nil != err {
return err
}
// 完整的请求地址
fullURL = r.getFullURL(serviceConfig, apiConfig, parameter)
fullURL, body = r.getFullURLAndBody(serviceConfig, apiConfig, parameter)
if response, err = client.Do(apiConfig.Method, fullURL, apiConfig.Header, bytes.NewReader(body)); nil != err {
return err
}
if responseBody, err = io.ReadAll(response.Body); nil != err {
return err
}
return nil
}
@ -295,12 +307,13 @@ func (r *request) GetHttpClient(header map[string]string, timeout ApiTimeout) *h
// Author : go_developer@163.com<白茶清欢>
//
// Date : 17:23 2022/6/30
func (r *request) getFullURL(serviceConfig *Service, apiConfig *Api, parameter map[string]interface{}) string {
func (r *request) getFullURLAndBody(serviceConfig *Service, apiConfig *Api, parameter map[string]interface{}) (string, []byte) {
fullURL := strings.ReplaceAll(serviceConfig.Domain+"/"+apiConfig.URI, "//", "/")
for name, val := range parameter {
fullURL = strings.ReplaceAll(fullURL, "{{"+name+"}}", fmt.Sprintf("%v", val))
}
parameterPair := make([]string, 0)
var body []byte
switch strings.ToUpper(apiConfig.Method) {
case http.MethodGet:
fallthrough
@ -318,10 +331,16 @@ func (r *request) getFullURL(serviceConfig *Service, apiConfig *Api, parameter m
_ = util.ConvertAssign(&valStr, val)
parameterPair = append(parameterPair, fmt.Sprintf("%v=%v", name, valStr))
}
case http.MethodPost:
fallthrough
case http.MethodPut:
fallthrough
case http.MethodDelete:
body, _ = json.Marshal(parameter)
}
query := strings.Join(parameterPair, "&")
if len(query) == 0 {
return strings.ReplaceAll(fullURL, "//", "/")
return strings.ReplaceAll(fullURL, "//", "/"), body
}
return strings.ReplaceAll(fullURL, "//", "/") + "?" + query
return strings.ReplaceAll(fullURL, "//", "/") + "?" + query, body
}