3

As title said, I am writing an API taking whatever json data that client posts.
Is there any way directly get a map[string]interface{} type data like bson.M?

I've tried simply looking up properties of gin.Context, is any of them would help if I miss something?

Joe
  • 117
  • 1
  • 6

2 Answers2

6
  1. Directly get []bytes from body of request
  2. Use json.Unmarshal() to convert []bytes into JSON like data: map[string]interface{}
func GetJsonData(c *gin.Context) {
    data, _ := ioutil.ReadAll(c.Request.Body)
    fmt.Println(string(data))

    var jsonData bson.M  // map[string]interface{}
    data, _ := ioutil.ReadAll(c.Request.Body)
    if e := json.Unmarshal(data, &jsonData); e != nil {
        c.JSON(http.StatusBadRequest, gin.H{"msg": e.Error()})
        return
    }
    c.JSON(http.StatusOK, jsonData)
}
Joe
  • 117
  • 1
  • 6
0

you can use json decoder

    type jsonPrametersMap map[string]interface{}
    var m jsonPrametersMap

    decoder := json.NewDecoder(bytes.NewReader(c.Request.Body))

    if err := decoder.Decode(&m); err != nil {
        fmt.Println(err)
        return
    }

playground here

Igor
  • 1,589
  • 15
  • 15