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

相当于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.

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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器