duanbushi1867
2016-03-27 14:27
浏览 989
已采纳

如何在golang中以标准方式从http请求获取数据?

I am trying to get the data from http request in golang. I am using net/http package. In my server handler I am trying to get the data from r.Body

body, err := ioutil.ReadAll(r.Body)
if err != nil {
    log.Printf("FATAL IO reader issue %s ", err.Error())
}

it works fine when I curl the service with some input data.

curl --data '{"AppName":"Proline","Properties":null,"Object":"","Timestamp":"2016:03:27 00:08:11"}' -XGET http://localhost:8081/api/services/test/

But when I try to call this service from ajax call r.Body is empty.

requestJSON = '{"AppName":"Proline","Properties":null,"Object":"","Timestamp":"2016:03:27 00:08:11"}'
$.ajax({
  type: "GET",
  url: "http://localhost:8081/api/services/test/",
  data: requestJSON,
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(data){alert(data);},
  failure: function(errMsg) {
      alert(errMsg);
  }
});

So I changed to read the input data from r.Form

r.ParseForm()
var body []byte
for key, _ := range r.Form {
    body = []byte(key)
    break
}

But now the curl request fails. Is there a standard way to retrieve input data from http request in golang? I am using Go 1.6. Could someone help me with this?

图片转代码服务由CSDN问答提供 功能建议

我正在尝试从golang中的http请求获取数据。 我正在使用net / http包。 在我的服务器处理程序中,我试图从r.Body

  body中获取数据,err:= ioutil.ReadAll(r.Body)
if err!= nil {\  n log.Printf(“ FAT IO读取器发出%s”,err.Error())
} 
   
 
 

当我将服务卷曲一些 输入数据。

  curl --data'{“ AppName”:“ Proline”,“ Properties”:null,“ Object”:“”,“ Timestamp”:“ 2016  :03:27 00:08:11“}'-XGET http:// localhost:8081 / api / services / test / 
   
 
 

但是当我尝试 从ajax调用此服务,调用r.Body为空。

  requestJSON ='{“ AppName”:“ Proline”,“ Properties”:null,“ Object”:“”,“ Timestamp”:“ 2016:03:27 00  :08:11“}'
 $ .ajax({
 type:” GET“,
 url:” http:// localhost:8081 / api / services / test /“,
数据:requestJSON,\  n contentType:“应用程序/ json; charset = utf-8”,
 dataType:“ json”,
成功:function(data){alert(data);},
失败:function(errMsg){
  alert(errMsg); 
} 
}); 
   
 
 

因此我更改为从 r.Form < /p>

r.ParseForm()
var主体[] byte 
用于密钥,_:=范围r.Form {
 body = [] byte(key)
 break \  n} 
   
 
 

但是现在curl请求失败了。 是否存在从golang中的http请求检索输入数据的标准方法? 我正在使用Go 1.6。 有人可以帮我吗?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题