在Golang JSON POST请求中编组为NonString类型

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!

You need to change the names of your Datablob values. You've told the JSON decoder that they're all named "id". You should try something like the following. Also, take a look at the json.Marshal description and how it describes the tags for structs and how the json library handles them. https://golang.org/pkg/encoding/json/#Marshal

type DataBlob struct {
    Timestamp string
    Metric_Id int `json:"metric_id,string,omitempty"`
    Value float32 `json:"value,string,omitempty"`
    Stderr float32 `json:"stderr,string,omitempty"`
}