proto/goutils/proto_build/tpls/http_grpc_method_var.tpl
2023-11-28 17:19:02 +08:00

104 lines
2.3 KiB
Smarty

package test
import (
"bytes"
"encoding/json"
"fmt"
"{{.ProjectName}}/server/config"
"fusen-basic/env"
"fusen-basic/utils/log"
"net/http"
"net/url"
"reflect"
"strings"
"time"
)
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
}