登录
首页 >  Golang >  Go问答

提取值时出现问题,Go 中的 r.PostFormValue 无法工作?

来源:stackoverflow

时间:2024-02-20 12:09:24 277浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《提取值时出现问题,Go 中的 r.PostFormValue 无法工作?》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

我正在尝试使用 net/http postformvalue 从 http post 请求正文(在我的简单 go http 服务器中)提取一个值,当我寻找任何键时,我的输出是一个空字符串,但在我的例子中,尝试获取 hub.secret 以用于 hmac 检查。我使用 postman 使用 gorilla/mux 路由器将请求发送到我的 localhost:8080 实例,并设置标头 content-type: application/x-www-form-urlencoded

我的处理程序看起来像这样:

func rootposthandler(w http.responsewriter, r *http.request) {

    var expectedmac []byte

    body, err := ioutil.readall(r.body)
    if err != nil {
        http.error(w, err.error(), http.statusinternalservererror)
        return
    }
    log.println("r.body is:", string(body)) // debug: print the request post body

    message := body // debug: set message just for extra clarity

    errparse := r.parseform()
    if errparse != nil {
        // handle err
    }
    secret := []byte(r.postformvalue("hub.secret"))
    log.println("secret is: ", string(secret))
    
    
    mac := hmac.new(sha256.new, secret)
    mac.write(message)
    expectedmac = mac.sum(nil)
    fmt.println("is hmac equal? ", hmac.equal(message, expectedmac))

    w.header().add("x-hub-signature", "sha256="+string(message))
}

r.body:

hub.callback=http%253A%252F%252Fweb-sub-client%253A8080%252FbRxvcmOcNk&hub.mode=subscribe&hub.secret=xTgSGLOtPNrBLLgYcKnL&hub.topic=%252Fa%252Ftopic

并且 print secret 等的输出是空字符串,这意味着它找不到 hub.secret,对吗?我在这里缺少什么?


正确答案


应用程序在此行读取请求正文到 eof:

body, err := ioutil.readall(r.body)

parseform 返回一个空表单,因为正文位于此行的 eof 处:

errparse := r.parseform()

请求正文是从网络连接中读取的。请求体无法被二次读取。

删除对 ioutil.readall 的调用或使用从 ioutil.readall 返回的数据创建新的正文读取器:

r.Body = io.NopCloser(bytes.NewReader(body))

以上就是《提取值时出现问题,Go 中的 r.PostFormValue 无法工作?》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>