go - 如何发送动态 json 键/值作为请求参数
问题描述
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)
}
- 我如何遍历参数是
interface
- 我如何获得密钥及其值
解决方案
您可以通过为 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
}
}
推荐阅读
- javascript - 例外:文档不可访问。请稍后再试。谷歌脚本
- python - Python flask_caching,根据传递的 Cookie 生成唯一页面
- unity3d - 如何修复错误 CS0234:命名空间“UnityEngine”中不存在类型或命名空间名称“Probuilder”(您是否缺少程序集引用?
- sql - QUERY 在 MS ACCESS 中返回分组数据中的下一行
- python - 如何将单引号添加到列表中的项目
- html - 如何将文本定位在中心图像的左侧(HTML)
- java - Java 可重入锁死锁
- slurm - 访问 SLURM 集群节点的暂存文件夹
- aws-lambda - 将 Kinesis 流中的数据重新驱动到 Lambda 函数
- ckan - 我可以检查服务器正在使用的配置参数吗?