proto/goutils/proto_build/tpls/http_grpc_method_var.tpl

104 lines
2.3 KiB
Smarty
Raw Normal View History

2023-11-27 09:36:02 +00:00
package test
import (
"bytes"
"encoding/json"
"fmt"
"{{.ProjectName}}/server/config"
"fusen-basic/env"
"fusen-basic/utils/log"
"net/http"
"net/url"
"reflect"
"strings"
2023-11-28 09:19:02 +00:00
"time"
2023-11-27 09:36:02 +00:00
)
var fusen *env.Fusen[config.Config]
var gatewayAddrress = "http://localhost:9900"
func HttpRequest(method, urlStr string, body interface{}, reqHandler func(*http.Request) error) (map[string]interface{}, error) {
var jsonBody *bytes.Buffer
var queryParams url.Values
if method == "GET" {
queryParams = JsonTagToURLValues(body)
jsonBody = bytes.NewBuffer(nil)
} else {
// 将请求体转换为JSON格式
jsonData, err := json.Marshal(body)
if err != nil {
log.Printf("Failed to marshal request body: %s\n", err.Error())
return nil, err
}
jsonBody = bytes.NewBuffer(jsonData)
log.Println(string(jsonData))
}
// 创建URL对象并添加查询参数
u, err := url.Parse(urlStr)
if err != nil {
fmt.Printf("Failed to parse URL: %s\n", err.Error())
return nil, err
}
u.RawQuery = queryParams.Encode()
// 创建HTTP请求
req, err := http.NewRequest(method, u.String(), jsonBody)
if err != nil {
fmt.Printf("Failed to create HTTP request: %s\n", err.Error())
return nil, err
}
// 设置请求头
req.Header.Set("Content-Type", "application/json")
if reqHandler != nil {
reqHandler(req)
}
// 发送HTTP请求
client := http.DefaultClient
client.Timeout = time.Second * 60
resp, err := client.Do(req)
if err != nil {
fmt.Printf("HTTP request failed: %s\n", err.Error())
return nil, err
}
if resp.StatusCode != 200 {
return nil, fmt.Errorf("%s", resp.Status)
}
defer resp.Body.Close()
// 解析响应体
var response map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&response)
if err != nil {
fmt.Printf("Failed to decode response body: %s\n", err.Error())
return nil, err
}
return response, nil
}
func JsonTagToURLValues(body interface{}) url.Values {
values := url.Values{}
v := reflect.ValueOf(body)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
t := v.Type()
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if field.IsExported() {
if jsonTag, ok := field.Tag.Lookup("json"); ok {
jtag := strings.Split(jsonTag, ",")[0]
value := v.Field(i).String()
values.Set(jtag, value)
}
}
}
return values
}