recipes2/internal/lib/api/response/response.go

50 lines
836 B
Go
Raw Normal View History

2024-01-23 12:22:16 +02:00
package response
import (
"fmt"
"strings"
"github.com/go-playground/validator/v10"
)
type Response struct {
Status string `json:"status"`
Error string `json:"error,omitempty"`
}
const (
StatusOK = "OK"
StatusError = "Error"
)
func OK() Response {
return Response{
Status: StatusOK,
}
}
func Error(msg string) Response {
return Response{
Status: StatusError,
Error: msg,
}
}
func ValidationError(errs validator.ValidationErrors) Response {
var errMsgs []string
for _, err := range errs {
switch err.ActualTag() {
case "required":
errMsgs = append(errMsgs, fmt.Sprintf("field %s is a required field", err.Field()))
default:
errMsgs = append(errMsgs, fmt.Sprintf("field %s is not valid", err.Field()))
}
}
return Response{
Status: StatusError,
Error: strings.Join(errMsgs, ", "),
}
}