I have struct like below:
type TextMessage struct {
Contacts []struct {
Profile struct {
Name string `json:"name"`
} `json:"profile"`
WaID string `json:"wa_id"`
} `json:"contacts" binding:"required,dive"`
Messages []struct {
From string `json:"from"`
ID string `json:"id"`
Timestamp string `json:"timestamp"`
Text struct {
Body string `json:"body"`
} `json:"text"`
Type string `json:"type"`
} `json:"messages" binding:"required,dive"`
}
However incoming Message have no text json tag, but validation is passed and no any error I saw:
var textMessage TextMessage
err = c.ShouldBindBodyWith(&textMessage, binding.JSON)
//answer: err is nil
Comment From: Tseian
Inside Gin using encoding/json
to decode body, like below.
package main
import (
"encoding/json"
"fmt"
"strings"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
textMessage := `{}`
decoder := json.NewDecoder(strings.NewReader(textMessage))
var p Person
if err := decoder.Decode(&p); err != nil {
panic(err)
}
fmt.Printf("Name: %s, Age: %d\n", p.Name, p.Age)
// Name: , Age: 0
}
deocder.Decode
works even if the textMessage is '{}'
. Maybe you should be more patient to check the http body.
Comment From: sabuhigr
It only works like that: https://go.dev/play/p/63gZN3SMKlC (can replace validator with binding tag)