51 lines
1.1 KiB
Go
51 lines
1.1 KiB
Go
package utils
|
|
|
|
import (
|
|
"approveflow/app/http/base"
|
|
"encoding/json"
|
|
"fmt"
|
|
"github.com/Superdanda/hade/framework/gin"
|
|
"net/http"
|
|
)
|
|
|
|
func ConvertToSpecificType[T any, I interface{}](items []I, convertFunc func(I) (T, bool)) ([]T, error) {
|
|
specificItems := make([]T, 0, len(items))
|
|
for i, item := range items {
|
|
if specificItem, ok := convertFunc(item); ok {
|
|
specificItems = append(specificItems, specificItem)
|
|
} else {
|
|
return nil, fmt.Errorf("invalid type at index %d", i)
|
|
}
|
|
}
|
|
return specificItems, nil
|
|
}
|
|
|
|
func ConvertToAbstractNodes[T any, I interface{}](items []T, toInterface func(T) I) []I {
|
|
nodes := make([]I, len(items))
|
|
for i, item := range items {
|
|
nodes[i] = toInterface(item)
|
|
}
|
|
return nodes
|
|
}
|
|
|
|
func QuickBind[T any](c *gin.Context) *T {
|
|
var params T
|
|
if err := c.ShouldBindJSON(¶ms); err != nil {
|
|
c.ISetStatus(http.StatusBadRequest).IJson(base.Fail("参数错误"))
|
|
return nil
|
|
}
|
|
return ¶ms
|
|
}
|
|
|
|
func Convert(origin interface{}, target interface{}) error {
|
|
data, err := json.Marshal(origin)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
err = json.Unmarshal(data, target)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|