12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- package request
-
- import (
- "net/http"
- "runtime"
-
- "github.com/gin-gonic/gin"
- "github.com/sirupsen/logrus"
- )
-
- type Checker interface {
- Check() error
- }
-
- func ParseSuccess(ctx *gin.Context, r interface{}, fs ...func() error) bool {
- if r != nil {
- if Error(ctx, http.StatusBadRequest, ctx.ShouldBind(r)) {
- return false
- }
-
- if checker, ok := r.(Checker); ok {
- return !Error(ctx, http.StatusBadRequest, checker.Check())
- }
- }
- for _, f := range fs {
- if Error(ctx, http.StatusBadRequest, f()) {
- return false
- }
- }
- return true
- }
-
- func Error(ctx *gin.Context, status int, err error) bool {
- if err == nil {
- return false
- }
- ctx.JSON(status, gin.H{"msg": err.Error()})
-
- if status == http.StatusInternalServerError {
- _, file, line, _ := runtime.Caller(1)
- logrus.WithField("err", err).Errorf("file:%s line:%d", file, line)
- }
- return true
- }
-
- func Success(ctx *gin.Context, data interface{}) {
- if data == nil {
- ctx.Status(http.StatusNoContent)
- return
- }
-
- switch ctx.Request.Method {
- case "GET", "PUT", "DELETE", "HEAD", "PATCH", "OPTIONS":
- ctx.JSON(http.StatusOK, data)
- case "POST":
- ctx.JSON(http.StatusCreated, data)
- default:
- ctx.JSON(http.StatusBadRequest, gin.H{"msg": "unsupported request method" + ctx.Request.Method})
- }
- }
|