【问题标题】:go - How to get request message body content?go - 如何获取请求消息正文内容?
【发布时间】:2016-03-31 03:00:37
【问题描述】:

我的客户端代码向服务器发送一个 AJAX 请求,其中包含一条消息

我如何从该请求消息正文中读取数据。在 NodeJS 的 Express 中,我使用这个:

    app.post('/api/on', auth.isLoggedIn, function(req, res){
                res.setHeader('Access-Control-Allow-Origin', '*');
                res.setHeader('Access-Control-Allow-Methods', 'POST');
                res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

                var url = req.body.url;
                // Later process
}

Go 中的 url = req.body.url 等价物是什么?

【问题讨论】:

  • 我想我误解了这个问题。您是在为 POST 的服务器处理程序寻找等效的 Go 代码,还是在寻找演示客户端响应的 Go 代码?
  • @JohnWeldon Go POST 服务器处理程序的代码,包括获取请求消息的正文。我编辑了问题以使其更清楚

标签: ajax node.js express go request


【解决方案1】:

如果请求正文是 URL 编码的,则使用 r.FormValue("url") 从请求中获取“url”值。

如果请求正文是 JSON,则使用 JSON decoderrequest body 解析为键入的值以匹配 JSON 的形状。

var data struct {
   URL string
}
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
    // handle error
}
// data.URL is "url" member of the posted JSON object.

【讨论】:

    【解决方案2】:

    Here 是一个简单的 http 处理程序示例:

    package main
    
    import (
        "bytes"
        "encoding/json"
        "fmt"
        "io/ioutil"
        "net/http"
    )
    
    func main() {
        http.HandleFunc("/", Handler)
        http.ListenAndServe(":8080", nil)
        // Running in playground will fail but this will start a server locally
    }
    
    type Payload struct {
        ArbitraryValue string `json:"arbitrary"`
        AnotherInt     int    `json:"another"`
    }
    
    func Handler(w http.ResponseWriter, r *http.Request) {
        body, err := ioutil.ReadAll(r.Body)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
    
        url := r.URL
        // Do something with Request URL
        fmt.Fprintf(w, "The URL is %q", url)
    
        payload := Payload{}
        err = json.NewDecoder(bytes.NewReader(body)).Decode(&payload)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        // Do something with payload
    
    }
    

    【讨论】:

    • 是的,这也很好用。我只是为这个例子修改了一些现有的示例代码。
    猜你喜欢
    • 2011-11-03
    • 1970-01-01
    • 2018-04-21
    • 2015-04-12
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-03
    相关资源
    最近更新 更多