Skip to content

Commit

Permalink
分离出servere逻辑
Browse files Browse the repository at this point in the history
  • Loading branch information
yumaojun03 committed Dec 25, 2023
1 parent 05c26e8 commit 2d21592
Show file tree
Hide file tree
Showing 30 changed files with 465 additions and 259 deletions.
11 changes: 2 additions & 9 deletions examples/http_go_restful/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,15 @@ import (

"github.com/emicklei/go-restful/v3"
"github.com/infraboard/mcube/v2/ioc"
"github.com/infraboard/mcube/v2/ioc/config/application"
"github.com/infraboard/mcube/v2/ioc/server"
)

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

// Ioc配置
req := ioc.NewLoadConfigRequest()
err := ioc.ConfigIocObject(req)
if err != nil {
panic(err)
}

// 启动应用
err = application.App().Start(context.Background())
err := server.Run(context.Background())
if err != nil {
panic(err)
}
Expand Down
3 changes: 3 additions & 0 deletions examples/kafka/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@ package main
import (
"fmt"

"github.com/infraboard/mcube/v2/ioc"
"github.com/infraboard/mcube/v2/ioc/config/kafka"
)

func main() {
ioc.DevelopmentSetup()

// 消息生产者
producer := kafka.Producer("test")
fmt.Println(producer)
Expand Down
3 changes: 3 additions & 0 deletions examples/lock/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@ import (
"context"
"time"

"github.com/infraboard/mcube/v2/ioc"
"github.com/infraboard/mcube/v2/ioc/config/lock"
)

func main() {
ioc.DevelopmentSetup()

// 创建一个key为test, 超时时间为10秒的锁
locker := lock.L().New("test", 10*time.Second)

Expand Down
22 changes: 22 additions & 0 deletions examples/log/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package main

import (
"context"

"github.com/infraboard/mcube/v2/ioc"
"github.com/infraboard/mcube/v2/ioc/config/logger"
)

func main() {
ioc.DevelopmentSetup()

gLogger := logger.L()
gLogger.Debug().Msg("this is global logger debug msg")

subLogger := logger.Sub("app1")
subLogger.Debug().Msg("this is app1 sub logger debug msg")

ctx := context.Background()
traceLogger := logger.T("app1").Trace(ctx)
traceLogger.Debug().Msg("this is app1 trace logger debug msg")
}
5 changes: 4 additions & 1 deletion examples/project/etc/application.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,15 @@ key = "this is your app key"
host = "127.0.0.1"
port = 8020

[metric]
enable = true

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

[log]
level = "debug"
Expand Down
16 changes: 4 additions & 12 deletions examples/project/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,17 @@ package main
import (
"context"

"github.com/infraboard/mcube/v2/ioc"
"github.com/infraboard/mcube/v2/ioc/config/application"
// 非业务模块
_ "github.com/infraboard/mcube/v2/ioc/apps/metric/gin"
"github.com/infraboard/mcube/v2/ioc/server"

// 加载业务模块
_ "github.com/infraboard/mcube/v2/examples/project/apps/helloworld/api"
_ "github.com/infraboard/mcube/v2/examples/project/apps/helloworld/impl"
)

func main() {
req := ioc.NewLoadConfigRequest()
// 配置文件默认路径: etc/applicaiton.toml
req.ConfigFile.Enabled = true
err := ioc.ConfigIocObject(req)
if err != nil {
panic(err)
}

// 启动应用, 应用会自动加载 刚才实现的Gin Api Handler
err = application.App().Start(context.Background())
err := server.Run(context.Background())
if err != nil {
panic(err)
}
Expand Down
20 changes: 15 additions & 5 deletions ioc/api.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package ioc

import (
"fmt"
"path"
"strings"

Expand Down Expand Up @@ -40,10 +39,13 @@ func LoadGinApi(pathPrefix string, root gin.IRouter) {
return
}

if pathPrefix != "" && !strings.HasPrefix(pathPrefix, "/") {
pathPrefix = "/" + pathPrefix
customPrefix := api.Meta().CustomPathPrefix
if customPrefix != "" {
pathPrefix = customPrefix
} else {
pathPrefix = path.Join(pathPrefix, api.Version(), api.Name())
}
api.Registry(root.Group(path.Join(pathPrefix, api.Version(), api.Name())))
api.Registry(root.Group(pathPrefix))
})
}

Expand All @@ -57,9 +59,17 @@ func LoadGoRestfulApi(pathPrefix string, root *restful.Container) {
}

pathPrefix = strings.TrimSuffix(pathPrefix, "/")

customPrefix := api.Meta().CustomPathPrefix
if customPrefix != "" {
pathPrefix = customPrefix
} else {
pathPrefix = path.Join(pathPrefix, api.Version(), api.Name())
}

ws := new(restful.WebService)
ws.
Path(fmt.Sprintf("%s/%s/%s", pathPrefix, api.Version(), api.Name())).
Path(pathPrefix).
Consumes(restful.MIME_JSON, form.MIME_POST_FORM, form.MIME_MULTIPART_FORM, yaml.MIME_YAML, yamlk8s.MIME_YAML).
Produces(restful.MIME_JSON, yaml.MIME_YAML, yamlk8s.MIME_YAML)
api.Registry(ws)
Expand Down
20 changes: 18 additions & 2 deletions ioc/apps/health/checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package health
import (
restfulspec "github.com/emicklei/go-restful-openapi/v2"
"github.com/emicklei/go-restful/v3"
"github.com/gin-gonic/gin"
h_response "github.com/infraboard/mcube/v2/http/response"
"github.com/infraboard/mcube/v2/http/restful/response"
"github.com/infraboard/mcube/v2/ioc/config/logger"
"github.com/rs/zerolog"
Expand Down Expand Up @@ -32,15 +34,15 @@ func (h *HealthChecker) WebService() *restful.WebService {
ws := new(restful.WebService)
ws.Path(h.HealthCheckPath)
tags := []string{"健康检查"}
ws.Route(ws.GET("/").To(h.Check).
ws.Route(ws.GET("/").To(h.RestfulHandleFunc).
Doc("查询服务当前状态").
Metadata(restfulspec.KeyOpenAPITags, tags).
Returns(200, "OK", HealthCheckResponse{}))

return ws
}

func (h *HealthChecker) Check(r *restful.Request, w *restful.Response) {
func (h *HealthChecker) RestfulHandleFunc(r *restful.Request, w *restful.Response) {
req := NewHealthCheckRequest()
resp, err := h.service.Check(
r.Request.Context(),
Expand All @@ -57,6 +59,20 @@ func (h *HealthChecker) Check(r *restful.Request, w *restful.Response) {
}
}

func (h *HealthChecker) GinHandleFunc(c *gin.Context) {
req := NewHealthCheckRequest()
resp, err := h.service.Check(
c.Request.Context(),
req,
)
if err != nil {
h_response.Failed(c.Writer, err)
return
}

h_response.Success(c.Writer, NewHealth(resp))
}

func NewHealthCheckRequest() *healthgrpc.HealthCheckRequest {
return &healthgrpc.HealthCheckRequest{}
}
Expand Down
52 changes: 52 additions & 0 deletions ioc/apps/metric/gin/metric.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package metric

import (
"github.com/gin-gonic/gin"
"github.com/infraboard/mcube/v2/ioc"
"github.com/infraboard/mcube/v2/ioc/apps/metric"
"github.com/infraboard/mcube/v2/ioc/config/http"
"github.com/infraboard/mcube/v2/ioc/config/logger"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/rs/zerolog"
)

func init() {
ioc.Api().Registry(&ginHandler{
Metric: metric.NewDefaultMetric(),
})
}

type ginHandler struct {
log *zerolog.Logger
ioc.ObjectImpl

*metric.Metric
}

func (h *ginHandler) Init() error {
h.log = logger.Sub(metric.AppName)
return nil
}

func (h *ginHandler) Name() string {
return metric.AppName
}

func (h *ginHandler) Version() string {
return "v1"
}

func (h *ginHandler) Meta() ioc.ObjectMeta {
meta := ioc.DefaultObjectMeta()
meta.CustomPathPrefix = h.Endpoint
return meta
}

func (h *ginHandler) Registry(r gin.IRouter) {
r.GET("/", func(ctx *gin.Context) {
// 基于标准库 包装了一层
promhttp.Handler().ServeHTTP(ctx.Writer, ctx.Request)
})

h.log.Info().Msgf("Get the Metric using http://%s%s", http.Get().Addr(), h.Endpoint)
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
package application
package metric

const (
AppName = "metric"
)

type METRIC_PROVIDER string

Expand All @@ -15,7 +19,7 @@ func NewDefaultMetric() *Metric {
}

type Metric struct {
Enable bool `json:"enable" yaml:"enable" toml:"enable" env:"ENABLE"`
Enable bool `json:"enable" yaml:"enable" toml:"enable" env:"METRIC_ENABLE"`
Provider METRIC_PROVIDER `toml:"provider" json:"provider" yaml:"provider" env:"METRIC_PROVIDER"`
Endpoint string `toml:"endpoint" json:"endpoint" yaml:"endpoint" env:"ENDPOINT"`
Endpoint string `toml:"endpoint" json:"endpoint" yaml:"endpoint" env:"METRIC_ENDPOINT"`
}
26 changes: 0 additions & 26 deletions ioc/apps/metric/metric.go

This file was deleted.

61 changes: 61 additions & 0 deletions ioc/apps/metric/restful/metric.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package metric

import (
restfulspec "github.com/emicklei/go-restful-openapi/v2"
"github.com/emicklei/go-restful/v3"
"github.com/infraboard/mcube/v2/ioc"
"github.com/infraboard/mcube/v2/ioc/apps/metric"
"github.com/infraboard/mcube/v2/ioc/config/http"
"github.com/infraboard/mcube/v2/ioc/config/logger"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/rs/zerolog"
)

func init() {
ioc.Api().Registry(&restfulHandler{
Metric: metric.NewDefaultMetric(),
})
}

type restfulHandler struct {
log *zerolog.Logger
ioc.ObjectImpl

*metric.Metric
}

func (h *restfulHandler) Init() error {
h.log = logger.Sub(metric.AppName)
return nil
}

func (h *restfulHandler) Name() string {
return metric.AppName
}

func (h *restfulHandler) Version() string {
return "v1"
}

func (h *restfulHandler) Meta() ioc.ObjectMeta {
meta := ioc.DefaultObjectMeta()
meta.CustomPathPrefix = h.Endpoint
return meta
}

func (h *restfulHandler) Registry(ws *restful.WebService) {
tags := []string{"健康检查"}
ws.Route(ws.
GET("/").
To(h.Check).
Doc("创建Job").
Metadata(restfulspec.KeyOpenAPITags, tags),
)

h.log.Info().Msgf("Get the Metric using http://%s%s", http.Get().Addr(), h.Endpoint)
}

func (h *restfulHandler) Check(r *restful.Request, w *restful.Response) {
// 基于标准库 包装了一层
promhttp.Handler().ServeHTTP(w, r.Request)
}
Loading

0 comments on commit 2d21592

Please sign in to comment.