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!