Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/fanesz/bindator
Binder + Validator for go restful API app with gin
https://github.com/fanesz/bindator
binder gin gin-gonic go go-package restful-api validator
Last synced: 4 days ago
JSON representation
Binder + Validator for go restful API app with gin
- Host: GitHub
- URL: https://github.com/fanesz/bindator
- Owner: fanesz
- Created: 2024-10-21T13:17:20.000Z (15 days ago)
- Default Branch: master
- Last Pushed: 2024-11-01T06:26:08.000Z (5 days ago)
- Last Synced: 2024-11-01T07:21:49.780Z (5 days ago)
- Topics: binder, gin, gin-gonic, go, go-package, restful-api, validator
- Language: Go
- Homepage:
- Size: 7.81 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Binder + Validator
A package that simplify binding and validating process for Gin framework using validator/v10.
```bash
go get github.com/fanesz/bindator
```Functions:
- bindator.BindBody()
- bindator.BindBodies()
- bindator.BindParam()
- bindator.BindParams()
- bindator.BindUri()
- bindator.BindUris()Example:
```go
package mainimport (
"net/http""github.com/fanesz/bindator"
"github.com/gin-gonic/gin"
)type User struct {
Email string `json:"email" validate:"required,email"`
Password string `json:"password" validate:"required"`
}func main() {
router := gin.Default()router.POST("/users", func(c *gin.Context) {
var user Userres := bindator.BindBody(c, &user)
if !res.Ok {
c.JSON(http.StatusBadRequest, res)
return
}c.JSON(http.StatusOK, gin.H{
"email": user.Email,
"password": user.Password,
})
})router.Run("127.0.0.1:8080")
}
```
### Fetch Result
#### When no body json provided:
```json
{
"message": "Invalid JSON data: unexpected end of JSON input"
}
```#### When invalid body json:
```json
{
"message": "Invalid body type",
"errors": [
{
"field": "email",
"message": "Field is required"
},
{
"field": "password",
"message": "Field is required"
}
]
}
```#### When invalid specific field (email, gte, lte, min, max, len):
```json
{
"message": "Invalid body type",
"errors": [
{
"field": "email",
"message": "Email is not valid"
}
]
}
```## Embedded Binding and Validating
Used when you need to bind an embedded struct, for example:
```go
type Company struct {
User User `json:"user"`
Contract Contract `json:"contract"`
}ok, res := bindator.BindBodies(c, &company)
```
note: you can't mix normal field with embedded field.