/
bind_data.go
59 lines (49 loc) · 1.64 KB
/
bind_data.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package handler
import (
"fmt"
"github.com/ankogit/wwc_social_rating/pkg/server/handler/response"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
"log"
"net/http"
)
// used to help extract validation errors
type invalidArgument struct {
Field string `json:"field"`
Value string `json:"value"`
Tag string `json:"tag"`
Param string `json:"param"`
}
// bindData is helper function, returns false if data is not bound
func bindData(c *gin.Context, req interface{}) bool {
log.Println(c.ContentType())
if c.ContentType() != "application/json" && c.ContentType() != "multipart/form-data" {
msg := fmt.Sprintf("%s only accepts Content-Type application/json", c.FullPath())
response.NewResponse(c, http.StatusBadRequest, msg)
return false
}
// Bind incoming json to struct and check for validation errors
if err := c.ShouldBind(req); err != nil {
log.Printf("Error binding data: %+v\n", err)
if errs, ok := err.(validator.ValidationErrors); ok {
// could probably extract this, it is also in middleware_auth_user
var invalidArgs []invalidArgument
for _, err := range errs {
invalidArgs = append(invalidArgs, invalidArgument{
err.Field(),
err.Value().(string),
err.Tag(),
err.Param(),
})
}
response.NewResponse(c, http.StatusBadRequest, "Invalid request parameters. See invalidArgs")
return false
}
// later we'll add code for validating max body size here!
// if we aren't able to properly extract validation errors,
// we'll fallback and return an internal server error
response.NewResponse(c, http.StatusHTTPVersionNotSupported, err.Error())
return false
}
return true
}