I'm having a little bit of trouble handling types in Golang. I'm making a POST router.
Consider the following struct
:
type DataBlob struct {
Timestamp string
Metric_Id int `json:"id,string,omitempty"`
Value float32 `json:"id,string,omitempty"`
Stderr float32 `json:"id,string,omitempty"`
}
This is my POST router using json.Unmarshal()
from a decoded stream:
func Post(w http.ResponseWriter, req * http.Request) {
body, err := ioutil.ReadAll(req.Body)
if err != nil {
panic()
}
var t DataBlob
err = json.Unmarshal(body, &t)
if err != nil {
panic()
}
fmt.Printf("%s
", t.Timestamp)
fmt.Printf("%d
", int(t.Metric_Id))
fmt.Printf("%f
", t.Value)
fmt.Printf("%f
", t.Stderr)
}
It seems that no matter what I make my values in my POST request:
{
"timestamp": "2011-05-16 15:36:38",
"metric_id": "28",
"value": "4.5",
"stderr": "8.5"
}
All the non-String values print as 0
or 0.000000
, respectively. It also doesn't matter if I try to type convert inline after-the-fact, as I did with t.Metric_Id
in the example.
If I edit my struct to just handle string
types, the values print correctly.
I also wrote a version of the POST router using json.NewDecoder()
:
func Post(w http.ResponseWriter, req * http.Request) {
decoder := json.NewDecoder(req.Body)
var t DataBlob
err := decoder.Decode(&t)
if err != nil {
panic()
}
fmt.Printf("%s
", t.Timestamp)
fmt.Printf("%d
", t.Metric_Id)
fmt.Printf("%f
", t.Value)
fmt.Printf("%f
", t.Stderr)
}
This is building off of functionality described in this answer, although the solution doesn't appear to work.
I appreciate your help!