You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I'm working on a project that needs use many handler functions for a single path, this is because we reuse some functions in others paths, for example: making validations. In many cases we need to work with the body, but for some reason when we use ctx.ReadJSON function for second time it throws unexpected end of JSON input
Is there a way to pass the body betwen the handlers or these error is a bug?
I'm letting a litte example snipet of the way we are working:
package main
import (
"github.com/kataras/iris"
validator "gopkg.in/go-playground/validator.v9"
"log"
)
// This is the spected structure of the JSON body
type niceStruct struct {
name string `json:"name" validate:"required"`
phone string `json:"phone" validate:"required"`
}
// This function make validations to the body
// and continues the process
func verifyBody(ctx iris.Context) {
var body niceStruct
if err := ctx.ReadJSON(&body); err != nil {
log.Println("Error on reading body")
log.Println(err)
return
}
validate := validator.New()
err := validate.Struct(body)
if err != nil {
log.Println("Error on validating body")
log.Println(err)
return
}
ctx.Next()
}
// This function use the body info
func sayHello(ctx iris.Context) {
var body niceStruct
if err := ctx.ReadJSON(&body); err != nil { // this is where throws errors
log.Println("Error on reading body")
log.Println(err)
return
}
hello := "Hello " + body.name
ctx.HTML(hello)
}
func main() {
app := iris.New()
app.Handle("GET", "/hello", verifyBody, sayHello)
app.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed))
}
The text was updated successfully, but these errors were encountered:
By-default, the ctx.ReadJSON and all read functions will read the body until EOF (io.ReadAll consumes the data readen, the whole body like the net/http and all web frameworks in Go, this is a basic thing to know).
However, Iris has a DisableBodyConsumptionOnUnmarshal option: app.Run(iris.Addr(...), iris.WithoutBodyConsumptionOnUnmarshal). This will give your handlers the opportunity to read the body again and again without consuming it by the first ReadJSON.
I'm working on a project that needs use many handler functions for a single path, this is because we reuse some functions in others paths, for example: making validations. In many cases we need to work with the body, but for some reason when we use ctx.ReadJSON function for second time it throws unexpected end of JSON input
Is there a way to pass the body betwen the handlers or these error is a bug?
I'm letting a litte example snipet of the way we are working:
The text was updated successfully, but these errors were encountered: