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

如何在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?

  • 写回答

1条回答 默认 最新

  • doujieju0397 2016-03-27 15:29
    关注

    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

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

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵