Note that there are some explanatory texts on larger screens.

plurals
  1. POGo's json decoder isn't working on the simplest possible input. Why?
    primarykey
    data
    text
    <p>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:</p> <pre><code>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, &amp;irec) fmt.Println("Input ", num, " bytes: ", string(inJson)) */ decoder := json.NewDecoder(r.Body) err := decoder.Decode(&amp;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) } </code></pre> <p>Now the test:</p> <pre><code>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 {} </code></pre> <p>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.</p> <p>When making said curl request, this appears as the output from the Println command:</p> <p>a: 0 b: 0 Sum: 0</p> <p>Seems pretty clear that the json fields line up to InputRec (just a and b) so what is wrong here?</p> <p>Thanks much!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload