http - 在 go 中处理 POST 请求

标签 http curl post go request

我在使用 gorilla/schema 解码 POST 请求时遇到问题。

我的代码正在创建一个基本的 http 服务器:

package main

import (
    "net/http"
    "gorilla/schema"
    "fmt"
    "log"
)

type Payload struct{
    slot_temp string
    data      string
    time      string
    device    string
    signal    string
}

func MyHandler(w http.ResponseWriter, r *http.Request) {
    err := r.ParseForm()

    if err != nil {
        fmt.Println("Error parsing form")
    }

    p := new(Payload)
    decoder := schema.NewDecoder()

    fmt.Println(r.PostForm)

    err = decoder.Decode(p, r.Form)

    if err != nil {
        fmt.Println("Error decoding")
    }
    fmt.Println(p.slot_temp)

}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", MyHandler)
    log.Fatal(http.ListenAndServe(":8082", mux))
}

我用

测试我
curl -X POST -H 'application/x-www-form-urlencoded' -d "slot_temp=34&data=22ltime=1495092909&device=1B3C29&signal=18.63" localhost:8082

但我得到以下输出

map[device:[1B3C29] signal:[18.63] slot_temp:[34] data:[22] time:[1495092909]]

// content of map and a blank line instead if the value of p.slot_temp

结构字段的内容从不打印。

我猜解码器有问题,但我无法弄清楚问题出在哪里。

谢谢

最佳答案

将您的结构字段名称更改为大写。您的解码器是外部包,它无权访问您的结构

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/schema"
)

type Payload struct {
    Slot_temp string
    Data      string
    Time      string
    Device    string
    Signal    string
}

func MyHandler(w http.ResponseWriter, r *http.Request) {
    err := r.ParseForm()

    if err != nil {
        fmt.Println("Error parsing form")
    }

    p := new(Payload)
    decoder := schema.NewDecoder()

    fmt.Println(r.PostForm)

    err = decoder.Decode(p, r.Form)

    if err != nil {
        fmt.Println("Error decoding")
    }
    fmt.Println(p.Slot_temp)

}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", MyHandler)
    log.Fatal(http.ListenAndServe(":8082", mux))
}

关于http - 在 go 中处理 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44047147/

相关文章:

android - Retrofit2:检索 JSONObject 不起作用

curl - 如何通过SSH主机发送请求

php - 使用 php 在 Moodle 中创建类(class)

php - 使用 PHP 和 Curl 登录我的网站表单

php - 这会产生某种永久循环吗? PHP 无法正常执行

dictionary - 如何将 POST 正文绑定(bind)到 map ?

c# - 如何读取内容长度为0的响应?

swift - PFFile url 返回以 http 而不是 https 开头的 url

Python basehttpserver 无法正确处理请求

php _POST查询参数失败,但硬编码文本查询成功