For this, you can use c.ShouldBindBodyWith
.
objA := formA{}
objB := formB{}
// This reads c.Request.Body and stores the result into the context.
if errA := c.ShouldBindBodyWith(&objA, binding.JSON); errA == nil {
c.String(http.StatusOK, `the body should be formA`)
c.String(http.StatusOK, `the body should be formB JSON`)
// And it can accepts other formats
} else if errB2 := c.ShouldBindBodyWith(&objB, binding.XML); errB2 == nil {
c.String(http.StatusOK, `the body should be formB XML`)
...
}
}
- stores body into the context before binding. This has
a slight impact to performance, so you should not use this method if you are
enough to call binding at once. - This feature is only needed for some formats —
JSON
,XML
,MsgPack
,ProtoBuf
. For other formats,Query
,Form
,FormPost
,FormMultipart
,
can be called by multiple times without any damage to
performance (See ).