Skip to content

Commit

Permalink
补充样例
Browse files Browse the repository at this point in the history
  • Loading branch information
yumaojun03 committed Jan 4, 2024
1 parent 7dbf778 commit aeae749
Show file tree
Hide file tree
Showing 4 changed files with 87 additions and 10 deletions.
3 changes: 0 additions & 3 deletions examples/project/etc/application.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,6 @@ key = "this is your app key"
host = "127.0.0.1"
port = 8020

[metric]
enable = true

[datasource]
host = "127.0.0.1"
port = 3306
Expand Down
21 changes: 21 additions & 0 deletions examples/simple/etc/application.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
[app]
name = "simple"
key = "this is your app key"

[http]
host = "127.0.0.1"
port = 8020

[datasource]
host = "127.0.0.1"
port = 3306
username = "root"
password = "123456"
database = "test"

[log]
level = "debug"

[log.file]
enable = true
file_path = "logs/app.log"
59 changes: 59 additions & 0 deletions examples/simple/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package main

import (
"context"
"net/http"

"github.com/gin-gonic/gin"
"github.com/infraboard/mcube/v2/ioc"
"github.com/infraboard/mcube/v2/ioc/config/datasource"
"github.com/infraboard/mcube/v2/ioc/server"
"gorm.io/gorm"
)

func main() {
// 注册HTTP接口类
ioc.Api().Registry(&ApiHandler{})

// 开启配置文件读取配置
server.DefaultConfig.ConfigFile.Enabled = true
server.DefaultConfig.ConfigFile.Path = "etc/application.toml"

// 启动应用
err := server.Run(context.Background())
if err != nil {
panic(err)
}
}

type ApiHandler struct {
// 继承自Ioc对象
ioc.ObjectImpl

// mysql db依赖
db *gorm.DB
}

// 覆写对象的名称, 该名称名称会体现在API的路径前缀里面
// 比如: /simple/api/v1/module_a/db_stats
// 其中/simple/api/v1/module_a 就是对象API前缀, 命名规则如下:
// <service_name>/<path_prefix>/<object_version>/<object_name>
func (h *ApiHandler) Name() string {
return "module_a"
}

// 初始化db属性, 从ioc的配置区域获取共用工具 gorm db对象
func (h *ApiHandler) Init() error {
h.db = datasource.DB()
return nil
}

// API路由
func (h *ApiHandler) Registry(r gin.IRouter) {
r.GET("/db_stats", func(ctx *gin.Context) {
db, _ := h.db.DB()
ctx.JSON(http.StatusOK, gin.H{
"data": db.Stats(),
})
})
}
14 changes: 7 additions & 7 deletions ioc/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,21 @@ type StoreManage interface {
LoadFromEnv(prefix string) error
}

// Object 内部服务实例, 不需要暴露
// Object接口, 需要注册到ioc空间托管的对象需要实现的方法
type Object interface {
// 对象初始化
// 对象初始化, 初始化对象的属性
Init() error
// 对象的名称
// 对象的名称, 根据名称可以从空间中取出对象
Name() string
// 对象版本
// 对象版本, 默认v1
Version() string
// 对象优先级
// 对象优先级, 根据优先级 控制对象初始化的顺序
Priority() int
// 对象的销毁
// 对象的销毁, 服务关闭时调用
Close(ctx context.Context) error
// 是否允许同名对象被替换, 默认不允许被替换
AllowOverwrite() bool
// 对象一些元数据
// 对象一些元数据, 对象的更多描述信息, 扩展使用
Meta() ObjectMeta
}

Expand Down

0 comments on commit aeae749

Please sign in to comment.