Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🔥 Request Validation #138

Closed
1995parham opened this issue Feb 13, 2020 · 1 comment
Closed

🔥 Request Validation #138

1995parham opened this issue Feb 13, 2020 · 1 comment

Comments

@1995parham
Copy link

Is your feature request related to a problem?
No

Describe the solution you'd like
Fiber has BodyParser function to parse request into the given interface. We can check that the interface has the Validation method and call it to see the parsed request is valid or not.

Describe alternatives you've considered
Validation may seem like an overkill feature, but I think it can reduce the handler code that is written for fiber.

Additional context

The following code shows a request with its validation method.

package request

import (
	"time"

	validation "github.com/go-ozzo/ozzo-validation"
	"github.com/go-ozzo/ozzo-validation/is"
)

// URL represents short URL creation request
type URL struct {
	URL    string     `json:"url"`
	Name   string     `json:"name"`
	Expire *time.Time `json:"expire"`
}

// Validate URL request
func (r URL) Validate() error {
	return validation.ValidateStruct(&r,
		validation.Field(&r.URL, validation.Required, is.URL),
	)
}

Fiber can check the validation method and call it if it is there on the given request.

@Fenny
Copy link
Member

Fenny commented Feb 13, 2020

@1995parham, we think that validation is up to the user. There are a 1000 ways to validate data, you could write your own middleware for it. Fiber is designed to be minimal but flexible.

package main

import (
  validation "github.com/go-ozzo/ozzo-validation"
  "github.com/gofiber/fiber"
)

type Person struct {
  Name string `json:"name" xml:"name" form:"name"`
  Pass string `json:"pass" xml:"pass" form:"pass"`
}

func (p Person) Validate() error {
  return validation.ValidateStruct(&p,
    validation.Field(&p.Name, validation.Required, validation.Length(5, 20)),
    validation.Field(&p.Pass, validation.Required, validation.Length(5, 50)),
  )
}

func main() {
  app := fiber.New()

  app.Post("/", func(c *fiber.Ctx) {
    var person Person

    c.BodyParser(&person)

    if err := person.Validate(); err != nil {
      c.Status(400).Send(err)
      return
    }

    c.Send("Hello, " + person.Name)
  })

  app.Listen(3000)
}

Run the following curl command the test the above snippet

curl -X POST -H "Content-Type: application/json" --data '{"name":"john","pass":"doe"}'  localhost:3000

This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants