gpt4 book ai didi

go - 如何发送动态 json 键/值作为请求参数

转载 作者:数据小太阳 更新时间:2023-10-29 03:47:33 24 4
gpt4 key购买 nike

package main

import (
"strings"
"net/http"
"encoding/json"
"fmt"
)

func main() {
j := `{"url":"http://localhost/test/take-request", "params":{"name":"John","age":"20"},"type":"get"}`
// k := `{"url":"http://localhost/test/take-request", "params":{"gender":"m","a":"20"},"type":"post"}`

request := map[string]interface{}{}

err := json.Unmarshal([]byte(j), &request)
if err != nil {
panic(err)
}
fmt.Println(request)
requestType = strings.ToUpper(request["type"]);
requestUrl = request["url"];

fmt.Println(request["params"])

// how do i get the keys and their values from params.
// note params is dynamic.
for _, v := range request["params"].(map[string]interface{}) {
// println(v)

switch t := v.(type) {
case string, []int:
fmt.Println(t)
default:
fmt.Println("wrong type")
}
}

sendRequest(requestType, requestUrl)
}

func sendRequest(type string, url string) string {
req, err := http.NewRequest(type, url, nil)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()

body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))
return string(body)
}
  1. 如何遍历 interface 的参数
  2. 如何获取 key 及其值

最佳答案

您可以通过对 JSON 解码使用适当的结构来极大地简化您的代码:

type Request struct {
URL string `json:"url"`
Params map[string]interface{} `json:"params"`
Type string `json:"type"`
}

然后你可以更简单地解码它:

request := &Request{}
if err := json.Unmarshal([]byte(j), &request); err != nil {
panic(err)
}

并访问这样的值:

requestType = request.Type
requestURL = request.URL
for key, value := range request.Params {
switch v := value.(type) {
case float64:
// handle numbers
case string:
// handle strings
}
}

关于go - 如何发送动态 json 键/值作为请求参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52198944/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com