我在使用 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/