登录
首页 >  Golang >  Go问答

发送包含动态 JSON 键/值的请求参数

来源:stackoverflow

时间:2024-03-13 08:12:21 227浏览 收藏

学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《发送包含动态 JSON 键/值的请求参数》,以下内容主要包含等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!

问题内容

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. 如何获取密钥及其值

解决方案


您可以通过使用正确的结构进行 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
    }
}

终于介绍完啦!小伙伴们,这篇关于《发送包含动态 JSON 键/值的请求参数》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>