github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/ginx/anyfn/out.go (about)

     1  package anyfn
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"reflect"
     7  
     8  	"github.com/bingoohuang/gg/pkg/ginx"
     9  	"github.com/gin-gonic/gin"
    10  )
    11  
    12  type OutSupport interface {
    13  	OutSupport(v interface{}, vs []interface{}, c *gin.Context) (bool, error)
    14  }
    15  
    16  type OutSupportFn func(v interface{}, vs []interface{}, c *gin.Context) (bool, error)
    17  
    18  func (o OutSupportFn) OutSupport(v interface{}, vs []interface{}, c *gin.Context) (bool, error) {
    19  	return o(v, vs, c)
    20  }
    21  
    22  func DirectDealerSupport(v interface{}, vs []interface{}, c *gin.Context) (bool, error) {
    23  	if dv, ok := v.(DirectDealer); ok {
    24  		dv.Deal(c)
    25  		return ok, nil
    26  	}
    27  
    28  	return false, nil
    29  }
    30  
    31  func ErrorSupport(v interface{}, vs []interface{}, c *gin.Context) (bool, error) {
    32  	if dv, ok := v.(error); ok {
    33  		c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", dv))
    34  		return ok, nil
    35  	}
    36  
    37  	return false, nil
    38  }
    39  
    40  func DefaultSupport(v0 interface{}, vs []interface{}, g *gin.Context) (bool, error) {
    41  	if v0 == nil {
    42  		return true, nil
    43  	}
    44  
    45  	switch reflect.Indirect(reflect.ValueOf(v0)).Kind() {
    46  	case reflect.Struct, reflect.Map, reflect.Interface, reflect.Slice:
    47  		g.Render(http.StatusOK, ginx.JSONRender{Data: v0})
    48  	default:
    49  		g.String(http.StatusOK, "%v", v0)
    50  	}
    51  
    52  	return true, nil
    53  }