1 Star 0 Fork 0

Erdian718 / di

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
di.go 1.28 KB
一键复制 编辑 原始数据 按行查看 历史
Erdian718 提交于 2023-09-03 15:06 . Implement Builder
// Package di provides a reflection-based dependency injection toolkit.
package di
import (
"fmt"
"reflect"
)
var (
typeError = reflect.TypeOf((*error)(nil)).Elem()
typeClean = reflect.TypeOf(Clean(nil))
)
// Creator represents a creator function.
type Creator func(reflect.Type) (reflect.Value, error)
// Closer is the interface that wraps the basic Close method.
type Closer interface {
Close() error
}
// Clean represents a clean function.
type Clean func() error
// Do does the clean up.
func (a Clean) Do() (err error) {
defer Catch("", &err)
return a()
}
// Catch catches the panic and format the error.
func Catch(format string, err *error) {
if x := recover(); x != nil {
if e, ok := x.(error); ok {
*err = e
} else {
*err = fmt.Errorf("%v", x)
}
}
if format != "" && *err != nil {
*err = fmt.Errorf(format, *err)
}
}
func typeAs(rt reflect.Type, itype any) (reflect.Type, error) {
if itype == nil {
return rt, nil
}
rit := reflect.TypeOf(itype)
if rit.Kind() != reflect.Pointer {
return nil, fmt.Errorf("not pointer to interface: %v", rit)
}
rit = rit.Elem()
if rit.Kind() != reflect.Interface {
return nil, fmt.Errorf("not interface: %v", rit)
}
if !rt.Implements(rit) {
return nil, fmt.Errorf("%v not implement %v", rt, rit)
}
return rit, nil
}
Go
1
https://gitee.com/erdian718/di.git
git@gitee.com:erdian718/di.git
erdian718
di
di
v0.1.0

搜索帮助