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 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择
  • ¥15 这款软件是什么?需要能满足我的需求
  • ¥15 SpringSecurityOauth2登陆前后request不一致