duanchuonong5370 2017-05-18 11:59
浏览 137
已采纳

在go中处理POST请求

I am having trouble decoding POST request with gorilla/schema.

My code is creating a basic http server:

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))
}

I test i with

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

But I get the following output

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

The content of the structure field is never printed.

I guess there is an issue with the decoder, but I can't figure out what is wrong.

Thanks

  • 写回答

1条回答 默认 最新

  • doufocheng6233 2017-05-18 12:21
    关注

    Change your struct fields name to uppercase. Your decoder is external package and it doesn't have access to your struct

    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))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入