duanquanhan2333 2013-06-23 17:03
浏览 39
已采纳

Go的json解码器无法在最简单的输入上运行。 为什么?

I'm preparing to write an AJAX type app in Go and this is a sample app to get familiar with how it would work. But it doesn't. The InputRec (irec) fields just have zeroes after the decode. First the source:

package main

import (
  "net/http"
  "encoding/json"
  "fmt"
  // "io/ioutil"
)

type InputRec struct {
  a, b float64
}

type RetRec struct {
  sum float64
}

func addHandler(w http.ResponseWriter, r *http.Request) {
  var outJson []byte
  var irec InputRec
  var orec RetRec

/*  inJson, err := ioutil.ReadAll(r.Body)
  num := len(inJson)
  if err != nil {
    panic("Error on reading body")
  }
  r.Body.Close()
  err = json.Unmarshal(inJson, &irec)
  fmt.Println("Input ", num, " bytes: ", string(inJson)) */

  decoder := json.NewDecoder(r.Body)
  err := decoder.Decode(&irec)
  if err != nil {
    panic("Error on JSON decode")
  }

  orec.sum = irec.a + irec.b
  fmt.Println("a: ", irec.a, " b: ", irec.b, " Sum: ", orec.sum)
  outJson, err = json.Marshal(orec)
  if err != nil {
    panic("Error on JSON encode")
  }

  w.Header().Set("Content-Type", "application/json")
  _, err = w.Write(outJson)
  if err != nil {
    panic("Error writing response")
  }
}

func main() {
  http.HandleFunc("/", addHandler)
  http.ListenAndServe(":1234", nil)
}

Now the test:

curl -X POST -i -d '{"a":5.4,"b":8.7}'  http://localhost:1234/
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 2
Date: Sun, 23 Jun 2013 17:01:08 GMT

{}

Note that I know the request body is making it to the function, because I have tried it with the commented out code instead of shorter json.Decoder lines, and it printed the request body as expected.

When making said curl request, this appears as the output from the Println command:

a: 0 b: 0 Sum: 0

Seems pretty clear that the json fields line up to InputRec (just a and b) so what is wrong here?

Thanks much!

  • 写回答

1条回答 默认 最新

  • dtsnx44260 2013-06-23 18:10
    关注

    I got it. The members of my structs had to be capitalized. :/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)