You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

92 lines
1.7 KiB

2 years ago
package response
2 years ago
import (
"encoding/json"
2 years ago
"git.diulo.com/mogfee/kit/errors"
2 years ago
"github.com/gin-gonic/gin"
"github.com/go-playground/form"
"net/http"
2 years ago
"unicode"
2 years ago
)
type result struct {
ctx *gin.Context
}
func New(ctx *gin.Context) *result {
return &result{ctx: ctx}
}
func (s *result) BindQuery(v any) error {
decoder := form.NewDecoder()
decoder.SetTagName("json")
2 years ago
err := decoder.Decode(v, s.ctx.Request.URL.Query())
if err != nil {
return err
}
return s.Validate(v)
}
func (s *result) Validate(v any) error {
if vv, ok := v.(interface {
Validate() error
}); ok {
return vv.Validate()
}
return nil
2 years ago
}
2 years ago
func (s *result) BindJSON(v any) error {
2 years ago
body := s.ctx.Request.Body
decoder := json.NewDecoder(body)
2 years ago
if err := decoder.Decode(v); err != nil {
return err
}
return s.Validate(v)
2 years ago
}
func (s *result) Error(err error) {
if err == nil {
return
}
//参数错误
if vv, ok := err.(ValidateError); ok {
s.Result(http.StatusBadRequest, "InvalidArgument", vv.ErrorName(), map[string]string{
2 years ago
lcfirst(vv.Field()): vv.Reason(),
2 years ago
})
return
}
2 years ago
gs := errors.FromError(err)
2 years ago
2 years ago
s.Result(int(gs.Code), gs.Reason, gs.Message, gs.Metadata)
2 years ago
}
2 years ago
func lcfirst(str string) string {
for i, v := range str {
return string(unicode.ToLower(v)) + str[i+1:]
}
return ""
}
2 years ago
type ValidateError interface {
Field() string
Reason() string
ErrorName() string
}
2 years ago
func (s *result) Success(data any) {
2 years ago
s.ctx.JSON(http.StatusOK, data)
2 years ago
}
2 years ago
func (s *result) Result(httpCode int, reason string, message string, metadata map[string]string) {
s.ctx.JSON(httpCode, gin.H{
"status": httpCode,
"reason": reason,
"message": message,
"metadata": metadata,
})
}
2 years ago
func (s *result) ServerResult(res any, err error) {
if err != nil {
s.Error(err)
} else {
s.Success(res)
}
}