Skip to content

Commit

Permalink
feat: 依赖注入重构&注解组件、任务组件封装完成
Browse files Browse the repository at this point in the history
  • Loading branch information
ithaiq committed Apr 26, 2022
1 parent 5259483 commit 6741131
Show file tree
Hide file tree
Showing 12 changed files with 255 additions and 37 deletions.
6 changes: 6 additions & 0 deletions example/classes/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (

type IndexClass struct {
*internal.GormAdapter
Age *internal.Value `prefix:"user.score"`
}

func NewIndexClass() *IndexClass {
Expand All @@ -28,7 +29,12 @@ func (i *IndexClass) GetModel(ctx *gin.Context) internal.Model {
return user
}

func (i *IndexClass) Test(c *gin.Context) string {
return "测试" + i.Age.String()
}

func (i *IndexClass) Build(t *internal.TGin) {
t.Handle("GET", "/index", i.GetIndex)
t.Handle("GET", "/test", i.Test)
t.Handle("GET", "/model/:id", i.GetModel)
}
4 changes: 4 additions & 0 deletions example/main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"fmt"
"github.com/ithaiq/tgin/example/classes"
"github.com/ithaiq/tgin/example/middlewares"
"github.com/ithaiq/tgin/internal"
Expand All @@ -11,5 +12,8 @@ func main() {
Beans(internal.NewGormAdapter()).
Attach(middlewares.NewUserMid()).
Mount("v1", classes.NewIndexClass()).
Task("0/3 * * * * *", func() {
fmt.Println("定时执行")
}).
Launch()
}
3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ go 1.17

require (
github.com/gin-gonic/gin v1.7.7
github.com/robfig/cron v1.2.0
gopkg.in/yaml.v2 v2.4.0
gorm.io/driver/mysql v1.3.3
gorm.io/gorm v1.23.4
)
Expand All @@ -27,5 +29,4 @@ require (
golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069 // indirect
golang.org/x/text v0.3.7 // indirect
google.golang.org/protobuf v1.28.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjY
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/robfig/cron v1.2.0 h1:ZjScXvvxeQ63Dbyxy76Fj3AT3Ut0aKsyd2/tl3DTMuQ=
github.com/robfig/cron v1.2.0/go.mod h1:JGuDeoQd7Z6yL4zQhZ3OPEVHB7fL6Ka6skscFHfmt2k=
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8=
github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
Expand Down
53 changes: 53 additions & 0 deletions internal/annotation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package internal

import (
"fmt"
"reflect"
"strings"
)

//Annotation 注解封装
type Annotation interface {
SetTag(tag reflect.StructTag)
String() string
}

var AnnotationList []Annotation

func IsAnnotation(t reflect.Type) bool {
for _, item := range AnnotationList {
if reflect.TypeOf(item) == t {
return true
}
}
return false
}

func init() {
AnnotationList = append(AnnotationList, new(Value))
}

//Value tag结构封装
type Value struct {
tag reflect.StructTag
BeanFactory *BeanFactory
}

func (v *Value) SetTag(tag reflect.StructTag) {
v.tag = tag
}

func (v *Value) String() string {
prefix := v.tag.Get("prefix")
if prefix == "" {
return ""
}
if config := v.BeanFactory.GetBean(new(SysConfig)); config != nil {
rV := GetConfigValue(config.(*SysConfig).Config, strings.Split(prefix, "."), 0)
if rV != nil {
return fmt.Sprintf("%v", rV)
}
return ""
}
return ""
}
72 changes: 72 additions & 0 deletions internal/bean.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package internal

import "reflect"

//BeanFactory 依赖注入工厂
type BeanFactory struct {
beans []interface{}
}

func NewBeanFactory() *BeanFactory {
bf := &BeanFactory{beans: make([]interface{}, 0)}
bf.beans = append(bf.beans, bf)
return bf
}

func (b *BeanFactory) setBean(beans ...interface{}) {
b.beans = append(b.beans, beans...)
}

func (b *BeanFactory) GetBean(bean interface{}) interface{} {
return b.getBean(reflect.TypeOf(bean))
}

func (b *BeanFactory) getBean(r reflect.Type) interface{} {
for _, p := range b.beans {
if r == reflect.TypeOf(p) {
return p
}
}
return nil
}

func (t *BeanFactory) Inject(v IClass) {
vRef := reflect.ValueOf(v).Elem()
vT := reflect.TypeOf(v).Elem()
for i := 0; i < vRef.NumField(); i++ {
f := vRef.Field(i)
if !f.IsNil() || f.Kind() != reflect.Ptr {
continue
}
if IsAnnotation(f.Type()) {
f.Set(reflect.New(f.Type().Elem()))
f.Interface().(Annotation).SetTag(vT.Field(i).Tag)
t.inject(f.Interface())
continue
}

if p := t.getBean(f.Type()); p != nil {
// vRef.Field(0).Type() --> 指针 *GormAdapter
// vRef.Field(0).Type().Elem() -->指针指向的对象 GormAdapter
f.Set(reflect.New(f.Type().Elem()))
f.Elem().Set(reflect.ValueOf(p).Elem())
}
}
}

func (b *BeanFactory) inject(object interface{}) {
rV := reflect.ValueOf(object)
if rV.Kind() == reflect.Ptr {
rV = rV.Elem()
}
for i := 0; i < rV.NumField(); i++ {
f := rV.Field(i)
if f.Kind() != reflect.Ptr || !f.IsNil() {
continue
}
if p := b.getBean(f.Type()); p != nil && f.CanInterface() {
f.Set(reflect.New(f.Type().Elem()))
f.Elem().Set(reflect.ValueOf(p).Elem())
}
}
}
5 changes: 0 additions & 5 deletions internal/class.go

This file was deleted.

21 changes: 20 additions & 1 deletion internal/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ type ServerConfig struct {
Name string
}

type UserConfig map[string]interface{}
type UserConfig map[interface{}]interface{}

//SysConfig 系统配置
type SysConfig struct {
Server *ServerConfig
Config UserConfig
Expand Down Expand Up @@ -42,3 +43,21 @@ func LoadConfigFile() []byte {
}
return b
}

// GetConfigValue 递归读取用户配置文件
func GetConfigValue(m UserConfig, prefix []string, index int) interface{} {
key := prefix[index]
if v, ok := m[key]; ok {
if index == len(prefix)-1 {
return v
} else {
index = index + 1
if mv, ok := v.(UserConfig); ok {
return GetConfigValue(mv, prefix, index)
} else {
return nil
}
}
}
return nil
}
1 change: 1 addition & 0 deletions internal/mid.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package internal

import "github.com/gin-gonic/gin"

//Mid 中间件
type Mid interface {
OnRequest(ctx *gin.Context) error
}
1 change: 1 addition & 0 deletions internal/resp.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ func init() {
}
}

//Responder 响应封装
type Responder interface {
RespondTo() gin.HandlerFunc
}
Expand Down
72 changes: 72 additions & 0 deletions internal/task.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package internal

import (
"github.com/robfig/cron"
"sync"
)

type TaskFunc func(params ...interface{})

var (
taskList chan *TaskExecutor
once sync.Once
onceCron sync.Once
taskCron *cron.Cron
)

//TaskExecutor 任务组件
type TaskExecutor struct {
f TaskFunc
p []interface{}
callback func()
}

func getTaskList() chan *TaskExecutor {
once.Do(func() {
taskList = make(chan *TaskExecutor)
})
return taskList
}

func init() {
ch := getTaskList()
go func() {
for t := range ch {
doTask(t)
}
}()
}

func doTask(t *TaskExecutor) {
go func() {
defer func() {
if t.callback != nil {
t.callback()
}
}()
t.Exec()
}()
}
func NewTaskExecutor(f TaskFunc, p []interface{}, callback func()) *TaskExecutor {
return &TaskExecutor{f: f, p: p, callback: callback}
}

func (t *TaskExecutor) Exec() {
t.f(t.p...)
}

func Task(f TaskFunc, callback func(), params ...interface{}) {
if f == nil {
return
}
go func() {
getTaskList() <- NewTaskExecutor(f, params, callback)
}()
}

func getCronTask() *cron.Cron {
onceCron.Do(func() {
taskCron = cron.New()
})
return taskCron
}
Loading

0 comments on commit 6741131

Please sign in to comment.