approveflow/app/utils/convert.go

51 lines
1.1 KiB
Go
Raw Normal View History

2024-11-14 17:02:41 +08:00
package utils
import (
"approveflow/app/http/base"
"encoding/json"
2024-11-15 16:53:35 +08:00
"fmt"
2024-11-14 17:02:41 +08:00
"github.com/Superdanda/hade/framework/gin"
"net/http"
)
2024-11-15 16:53:35 +08:00
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
}
2024-11-14 17:02:41 +08:00
func QuickBind[T any](c *gin.Context) *T {
var params T
if err := c.ShouldBindJSON(&params); err != nil {
c.ISetStatus(http.StatusBadRequest).IJson(base.Fail("参数错误"))
return nil
}
return &params
}
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
}