dongxianghui3709 2015-05-03 07:17
浏览 169
已采纳

相当于go http请求有效载荷中的curl --data

For the purpose of setting a K/V in a NoSQL storage, I need to create an equivalent to the following curl command in go:

curl -H "Content-Type: text/xml" --data '[...]' http://localhost:8000/test/testrow/test:testcolumn

I am trying to use something in the lines of the following code for that purpose, although I am unable to find how to set the binary data []byte(value) as a POST payload.

func setColumn(table string, key string, col string, value string) {

url := "http://localhost:8123/" + table + "/" + key + "/" + col
req, err := http.NewRequest("POST", url, nil)
req.Header.Set("Content-Type", "application/octet-stream")

data = []byte(value)

client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
    // handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))

}

So, how to map the data payload within the POST request ? Any indicators are welcome.

  • 写回答

1条回答 默认 最新

  • doubingqi5829 2015-05-03 08:34
    关注

    In order to post any data you should pass the value instead of nil in the Newrequest method.

    This should work

    func setColumn(table string, key string, col string, value string) {
    
        url := "http://localhost:8123/" + table + "/" + key + "/" + col
        **data := bytes.NewReader([]byte(value))**
        req, err := http.NewRequest("POST", url, **data**)
        req.Header.Set("Content-Type", "application/octet-stream")
    
        client := &http.Client{}
        resp, err := client.Do(req)
        if err != nil {
            // handle error
        }
        defer resp.Body.Close()
        body, err := ioutil.ReadAll(resp.Body)
        fmt.Println(string(body))
    }
    

    Most of the NoSQL Servers has GO API use them instad of creating your own HTTP request.

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

报告相同问题?

悬赏问题

  • ¥50 husky+jaco2实现在gazebo与rviz中联合仿真
  • ¥15 dpabi预处理报错:Error using y_ExtractROISignal (line 251)
  • ¥15 在虚拟机中配置flume,无法将slave1节点的文件采集到master节点中
  • ¥15 husky+kinova jaco2 仿真
  • ¥15 zigbee终端设备入网失败
  • ¥15 金融监管系统怎么对7+4机构进行监管的
  • ¥15 硬件IIC从模式的数据发送,中断数据的接收,不能用HAL库(按照时序图)
  • ¥20 QAxWidget上显示一个word文档后,如何直接在该QAxWidget上修改和保存word文档
  • ¥15 Simulink仿真报错,请问如何解决
  • ¥20 宝塔面板无法添加Node项目,一直处于正在添加脚本页面