refact: refactored api.rest utility functions into separate file.

This commit is contained in:
evilsocket 2018-01-17 17:04:15 +01:00
parent ec93bd82f2
commit 4f1c508a7c
2 changed files with 45 additions and 39 deletions

45
modules/api_rest_utils.go Normal file
View file

@ -0,0 +1,45 @@
package modules
import (
"encoding/json"
"io"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
)
type CommandRequest struct {
Command string `json:"cmd"`
}
type APIResponse struct {
Success bool `json:"success"`
Message string `json:"msg"`
}
func SafeBind(c *gin.Context, obj interface{}) error {
decoder := json.NewDecoder(io.LimitReader(c.Request.Body, 100*1024))
if binding.EnableDecoderUseNumber {
decoder.UseNumber()
}
if err := decoder.Decode(obj); err != nil {
return err
}
if binding.Validator == nil {
return nil
}
return binding.Validator.ValidateStruct(obj)
}
func BadRequest(c *gin.Context, optMsg ...string) {
msg := "Bad Request"
if len(optMsg) > 0 {
msg = optMsg[0]
}
c.JSON(400, APIResponse{
Success: false,
Message: msg,
})
c.Abort()
}