dtcmadj31951 2013-09-11 00:05
浏览 342
已采纳

正确使用map [string] interface {}?

I have two related questions, I did not want to open a new thread for both questions:

Given the following code:

1    type Request struct {
2       Values map[string]interface{}
3    }
4
5    func (r Request) Send() {
6       client := &http.Client{}
7       resp, _ := http.Post("http://example.com", "text/json", &r.Values)
8    }

The idea is to be able to send a block of an unknown amount key => value, key => key => value, etc. to our API endpoint.

Question 1:

How do I assign to Request.Values? An example use case we may need to employ is the following (Excuse the PHP Code, we're transitioning):

'name' => [ $first, $last ],
'address' => [ 'city' => 'city', 'state' => 'state' ],
'country' => 'US'

In this example we have key => value, key => [ values ], and key => [ key => value ]

How can I take that and assign the exact same values to Request.Values?

Question 2:

Obviously Values is of type map[string]interface{} , how can I convert that to type io.Reader so I can send the values to the server?

Any guidance is greatly appreciated on both questions.

  • 写回答

1条回答 默认 最新

  • drhwb470572 2013-09-11 02:03
    关注

    Question 1

    You can assign values to Request.Values just like with any other value.

    Example (on play):

    x := map[string]interface{}{
        "foo": []string{"a","b"},
        "bar": "foo",
        "baz": 10.4,
    }
    

    Question 2

    You are in need of an intermediate format, for example JSON.

    With this package you can marshal your Request struct to a JSON string, transfer said string and parse it on the other (PHP?) side.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题