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 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图