How to get the data from http request in a standard way in golang?

huangapple go评论90阅读模式
英文:

How to get the data from http request in a standard way in golang?

问题

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

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

当我使用一些输入数据对服务进行curl时,它可以正常工作。

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/",
  data: requestJSON,
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(data){alert(data);},
  failure: function(errMsg) {
      alert(errMsg);
  }
});

所以我改为从r.Form中读取输入数据。

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

但现在curl请求失败了。在Golang中,有没有一种标准的方法来获取HTTP请求中的输入数据?我正在使用Go 1.6版本。有人可以帮助我吗?

英文:

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?

答案1

得分: 2

发送一个带有GET请求的有意义的主体是不被规范允许的。所以你的浏览器可能发送了一个空的主体。你可以使用POST代替。r.ParseForm()不起作用是因为它期望主体被application/x-www-form-urlencoded编码,而不是json

如果GET更适合将用户输入发送到服务器的请求处理程序,你可以使用URL查询参数。

引用JQuery.ajax() 文档中的data参数,

> 要发送到服务器的数据。如果不是字符串,它将被转换为查询字符串。对于GET请求,它将附加到URL上。请参阅processData选项以防止此自动处理。对象必须是键/值对。

所以你可以这样做,

$.ajax({
  type: "GET",
  url: "http://localhost:8081/api/services/test/",
  data: {AppName: "Proline", Properties:null, Object: ""}, // 一个对象,而不是一个字符串。
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(data){alert(data)}
})

在服务器端,

params := r.URL.Query()
params.Get('AppName') // 返回 'Proline'

参考文档:https://golang.org/pkg/net/url/#URL.Query

英文:

Sending a meaningful body with a GET request is disallowed by the spec. So your browser is probably sending an empty body. You can use POST instead. Its unsurprising that r.ParseForm() is not working because it expects the body to be encoded by application/x-www-form-urlencoded. Not json.

If GET is more appropriate to send the user inputs to your server's request handlers you can use url query parameters.

Quoting JQuery.ajax() docs for data parameter,

> Data to be sent to the server. It is converted to a query string, if
> not already a string. It's appended to the url for GET-requests. See
> processData option to prevent this automatic processing. Object must
> be Key/Value pairs.

So you can do,

$.ajax({
  type: "GET",
  url: "http://localhost:8081/api/services/test/",
  data: {AppName: "Proline", Properties:null, Object: ""}, // An object, not a string.
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(data){alert(data)}
})

An in the server,

params := r.URL.Query()
params.Get('AppName') // returns 'Proline'

See docs: https://golang.org/pkg/net/url/#URL.Query

huangapple
  • 本文由 发表于 2016年3月27日 22:27:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/36248468.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定