func InsertApData(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
fmt.Printf("Request Body : ", decoder)
var apdata models.ApData
err := decoder.Decode(&apdata)
check(b.E(err))
_, err2 := stmt.InsertApData.Exec(apdata.Mac, apdata.RssiMax, apdata.RssiMin, apdata.LocDefId)
check(b.E(err2))
}
and data type for db
type ApData struct {
ID int `db:"id"`
Mac string `db:"mac"`
RssiMax uint64 `db:"rssi_max"`
RssiMin uint16 `db:"rssi_min"`
LocDefId uint64 `db:"loc_def_id"`
}
Why returning
Request Body : %!(EXTRA *json.Decoder=&{0xc820012b00 [] {[] 0 { false [] false 0 0} { false [] false 0 0} false} 0 { false [] false 0 0} 0 []})
also json :
{
"mac":"01:0a:95:9d:68:20",
"rssi_max":-73.50,
"rssi_min":-50.02,
"loc_def_id":1
}
If you examine the source code for json.Decoder
,
...
type Decoder struct {
r io.Reader
buf []byte
d decodeState
scanp int // start of unread data in buf
scan scanner
err error
tokenState int
tokenStack []int
}
func NewDecoder(r io.Reader) *Decoder {
return &Decoder{r: r}
}
...
you can see that NewDecoder
only sets the r
field, and that is what you are observing in the output of fmt.Printf
.
Until you execute err := decoder.Decode(&apdata)
, your structure will not be filled in. What you are seeing in the output is the content of the decoder, not the body or your structure.
If you print your structure after running err := decoder.Decode(&apdata)
, it contains proper data:
package main
import (
"fmt"
"encoding/json"
"strings"
)
func main() {
input := `{
"mac":"01:0a:95:9d:68:20",
"rssi_max":-73.50,
"rssi_min":-50.02,
"loc_def_id":1
}`
decoder := json.NewDecoder(strings.NewReader(input))
var apdata struct {
ID int `db:"id"`
Mac string `json:"mac" db:"mac"`
RssiMax uint64 `json:"rssi_max" db:"rssi_max"`
RssiMin uint16 `json:"rssi_min" db:"rssi_min"`
LocDefId uint64 `json:"loc_def_id" db:"loc_def_id"`
}
_ = decoder.Decode(&apdata)
fmt.Printf("appdata : %+v
", apdata)
}
Output:
appdata : {ID:0 Mac:01:0a:95:9d:68:20 RssiMax:0 RssiMin:0 LocDefId:1}
The RssiMax
and RssiMin
are zero because they are unsigned ints receiving negative values.