Skip to content

Commit a5ee4c1

Browse files
committed
补充cors
1 parent 2428cdb commit a5ee4c1

File tree

10 files changed

+228
-90
lines changed

10 files changed

+228
-90
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package impl
2+
3+
import "github.com/prometheus/client_golang/prometheus"
4+
5+
func NewEventCollect() *EventCollect {
6+
return &EventCollect{
7+
errCountDesc: prometheus.NewDesc(
8+
"save_event_error_count",
9+
"事件入库失败个数统计",
10+
[]string{},
11+
prometheus.Labels{"service": "maudit"},
12+
),
13+
}
14+
}
15+
16+
// 收集事件指标的采集器
17+
type EventCollect struct {
18+
errCountDesc *prometheus.Desc
19+
// 需要自己根据实践情况来维护这个变量
20+
errCount int
21+
}
22+
23+
func (c *EventCollect) Inc() {
24+
c.errCount++
25+
}
26+
27+
// 指标元数据注册
28+
func (c *EventCollect) Describe(ch chan<- *prometheus.Desc) {
29+
ch <- c.errCountDesc
30+
}
31+
32+
// 指标的值的采集
33+
func (c *EventCollect) Collect(ch chan<- prometheus.Metric) {
34+
ch <- prometheus.MustNewConstMetric(c.errCountDesc, prometheus.GaugeValue, float64(c.errCount))
35+
}

examples/project/apps/helloworld/impl/impl.go

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
package impl
22

33
import (
4+
"errors"
5+
46
"github.com/infraboard/mcube/v2/ioc"
57
"github.com/infraboard/mcube/v2/ioc/config/datasource"
8+
"github.com/prometheus/client_golang/prometheus"
69
"gorm.io/gorm"
710
)
811

@@ -12,7 +15,8 @@ func init() {
1215

1316
// 业务逻辑实现类
1417
type HelloServiceImpl struct {
15-
db *gorm.DB
18+
db *gorm.DB
19+
colector *EventCollect
1620

1721
ioc.ObjectImpl
1822
}
@@ -22,10 +26,21 @@ func (i *HelloServiceImpl) Init() error {
2226
// 从Ioc总获取GORM DB对象, GORM相关配置已经托管给Ioc
2327
// Ioc会负责GORM的配置读取和为你初始化DB对象实例,以及关闭
2428
i.db = datasource.DB()
29+
30+
// 将采集器注册到默认注册表
31+
i.colector = NewEventCollect()
32+
prometheus.MustRegister(i.colector)
2533
return nil
2634
}
2735

2836
// 具体业务逻辑
2937
func (i *HelloServiceImpl) Hello() string {
38+
39+
// 模拟存储失败报错, 然后调用采集器纪录状态
40+
err := errors.New("save event error")
41+
if err != nil {
42+
i.colector.Inc()
43+
}
44+
3045
return "hello world"
3146
}

examples/project/main.go

Lines changed: 58 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,16 @@ package main
22

33
import (
44
"context"
5+
"fmt"
6+
"net/http"
57

8+
"github.com/emicklei/go-restful/v3"
9+
"github.com/gin-gonic/gin"
10+
"github.com/infraboard/mcube/v2/ioc/config/grpc"
11+
ioc_http "github.com/infraboard/mcube/v2/ioc/config/http"
612
"github.com/infraboard/mcube/v2/ioc/server"
713

8-
// 注入Metric模块
14+
// metric 模块
915
_ "github.com/infraboard/mcube/v2/ioc/apps/metric/gin"
1016

1117
// 加载业务模块
@@ -15,8 +21,55 @@ import (
1521

1622
func main() {
1723
server.DefaultConfig.ConfigFile.Enabled = true
18-
err := server.Run(context.Background())
19-
if err != nil {
20-
panic(err)
21-
}
24+
server.DefaultConfig.ConfigFile.Path = "etc/application.toml"
25+
26+
// 直接启动
27+
// err := server.Run(context.Background())
28+
// if err != nil {
29+
// panic(err)
30+
// }
31+
32+
// 启动前 设置
33+
server.SetUp(func() {
34+
// 开启GRPC服务注册与注销
35+
grpc.Get().PostStart = func(ctx context.Context) error {
36+
return nil
37+
}
38+
grpc.Get().PreStop = func(ctx context.Context) error {
39+
return nil
40+
}
41+
42+
// HTTP业务路由加载之前
43+
rb := ioc_http.Get().GetRouterBuilder()
44+
rb.BeforeLoadHooks(func(r http.Handler) {
45+
// Gin框架
46+
if router, ok := r.(*restful.Container); ok {
47+
// GoRestful Router对象
48+
fmt.Println(router)
49+
}
50+
51+
// GoRestful 框架
52+
if router, ok := r.(*gin.Engine); ok {
53+
// Gin Engine对象
54+
fmt.Println(router)
55+
}
56+
})
57+
// HTTP业务路由加载之后
58+
rb.AfterLoadHooks(func(r http.Handler) {
59+
// Gin框架
60+
if router, ok := r.(*restful.Container); ok {
61+
// GoRestful Router对象
62+
fmt.Println(router)
63+
}
64+
65+
// GoRestful 框架
66+
if router, ok := r.(*gin.Engine); ok {
67+
// Gin Engine对象
68+
fmt.Println(router)
69+
}
70+
})
71+
72+
// 补充Grpc 中间件
73+
grpc.Get().AddInterceptors()
74+
}).Run(context.Background())
2275
}

ioc/apps/apidoc/restful/swagger.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ func (h *SwaggerApiDoc) Registry(ws *restful.WebService) {
5252
ws.Route(ws.GET("/").To(func(r *restful.Request, w *restful.Response) {
5353
w.WriteAsJson(swagger)
5454
}))
55-
h.log.Info().Msgf("Get the Health using http://%s%s", http.Get().Addr(), h.Path)
55+
h.log.Info().Msgf("Get the API Doc using http://%s%s", http.Get().Addr(), h.Path)
5656
}
5757

5858
// API Doc

ioc/config/cors/cors.go

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package cors
2+
3+
import (
4+
"net/http"
5+
6+
"github.com/emicklei/go-restful/v3"
7+
"github.com/infraboard/mcube/v2/ioc"
8+
ioc_http "github.com/infraboard/mcube/v2/ioc/config/http"
9+
)
10+
11+
func init() {
12+
ioc.Config().Registry(&CORS{
13+
Enabled: true,
14+
AllowedHeaders: []string{"*"},
15+
AllowedDomains: []string{"*"},
16+
AllowedMethods: []string{"HEAD", "OPTIONS", "GET", "POST", "PUT", "PATCH", "DELETE"},
17+
})
18+
}
19+
20+
type CORS struct {
21+
ioc.ObjectImpl
22+
23+
Enabled bool `toml:"enabled" json:"enabled" yaml:"enabled" env:"CORS_ENABLED"`
24+
AllowedHeaders []string `json:"cors_allowed_headers" yaml:"cors_allowed_headers" toml:"cors_allowed_headers" env:"CORS_ALLOWED_HEADERS" envSeparator:","`
25+
AllowedDomains []string `json:"cors_allowed_domains" yaml:"cors_allowed_domains" toml:"cors_allowed_domains" env:"CORS_ALLOWED_DOMAINS" envSeparator:","`
26+
AllowedMethods []string `json:"cors_allowed_methods" yaml:"cors_allowed_methods" toml:"cors_allowed_methods" env:"CORS_ALLOWED_METHODS" envSeparator:","`
27+
}
28+
29+
func (m *CORS) Name() string {
30+
return AppName
31+
}
32+
33+
func (m *CORS) Init() error {
34+
rb := ioc_http.Get().GetRouterBuilder()
35+
36+
// 将中间件添加到Router中
37+
if m.Enabled {
38+
rb.BeforeLoadHooks(func(h http.Handler) {
39+
switch r := h.(type) {
40+
case *restful.Container:
41+
cors := restful.CrossOriginResourceSharing{
42+
AllowedHeaders: m.AllowedHeaders,
43+
AllowedDomains: m.AllowedDomains,
44+
AllowedMethods: m.AllowedMethods,
45+
CookiesAllowed: false,
46+
Container: r,
47+
}
48+
r.Filter(cors.Filter)
49+
}
50+
})
51+
}
52+
return nil
53+
}
54+
55+
func (i *CORS) Priority() int {
56+
return -10
57+
}

ioc/config/cors/interface.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package cors
2+
3+
import "github.com/infraboard/mcube/v2/ioc"
4+
5+
const (
6+
AppName = "cors"
7+
)
8+
9+
func Get() *CORS {
10+
return ioc.Config().Get(AppName).(*CORS)
11+
}

ioc/config/http/gin.go

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,32 +9,28 @@ import (
99

1010
func NewGinRouterBuilder() *GinRouterBuilder {
1111
return &GinRouterBuilder{
12-
conf: &BuildConfig{},
12+
RouterBuilderHooks: NewRouterBuilderHooks(),
1313
}
1414
}
1515

1616
type GinRouterBuilder struct {
17-
conf *BuildConfig
18-
}
19-
20-
func (b *GinRouterBuilder) Config(c *BuildConfig) {
21-
b.conf = c
17+
*RouterBuilderHooks
2218
}
2319

2420
func (b *GinRouterBuilder) Build() (http.Handler, error) {
2521
r := gin.Default()
2622

2723
// 装载Ioc路由之前
28-
if b.conf.BeforeLoad != nil {
29-
b.conf.BeforeLoad(r)
24+
for _, fn := range b.Before {
25+
fn(r)
3026
}
3127

3228
// 装置子服务路由
3329
ioc.LoadGinApi(Get().PathPrefix, r)
3430

3531
// 装载Ioc路由之后
36-
if b.conf.AfterLoad != nil {
37-
b.conf.AfterLoad(r)
32+
for _, fn := range b.After {
33+
fn(r)
3834
}
3935

4036
return r, nil

ioc/config/http/http.go

Lines changed: 6 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,7 @@ func init() {
2626
IdleTimeoutSecond: 300,
2727
MaxHeaderSize: "16kb",
2828
EnableTrace: true,
29-
Cors: CORS{
30-
Enabled: false,
31-
AllowedHeaders: []string{"*"},
32-
AllowedDomains: []string{"*"},
33-
AllowedMethods: []string{"HEAD", "OPTIONS", "GET", "POST", "PUT", "PATCH", "DELETE"},
34-
},
35-
WEB_FRAMEWORK: WEB_FRAMEWORK_AUTO,
29+
WEB_FRAMEWORK: WEB_FRAMEWORK_AUTO,
3630
routerBuilders: map[WEB_FRAMEWORK]RouterBuilder{
3731
WEB_FRAMEWORK_GO_RESTFUL: NewGoRestfulRouterBuilder(),
3832
WEB_FRAMEWORK_GIN: NewGinRouterBuilder(),
@@ -41,7 +35,6 @@ func init() {
4135
WEB_FRAMEWORK_GO_RESTFUL: 0,
4236
WEB_FRAMEWORK_GIN: 0,
4337
},
44-
RouterBuildConfig: &BuildConfig{},
4538
})
4639
}
4740

@@ -72,23 +65,15 @@ type Http struct {
7265
// header最大大小
7366
MaxHeaderSize string `json:"max_header_size" yaml:"max_header_size" toml:"max_header_size" env:"MAX_HEADER_SIZE"`
7467

75-
// SSL启用参数
76-
EnableSSL bool `json:"enable_ssl" yaml:"enable_ssl" toml:"enable_ssl" env:"ENABLE_SSL"`
77-
CertFile string `json:"cert_file" yaml:"cert_file" toml:"cert_file" env:"CERT_FILE"`
78-
KeyFile string `json:"key_file" yaml:"key_file" toml:"key_file" env:"KEY_FILE"`
79-
8068
// 开启Trace
8169
EnableTrace bool `toml:"enable_trace" json:"enable_trace" yaml:"enable_trace" env:"ENABLE_TRACE"`
82-
// cors配置
83-
Cors CORS `toml:"cors" json:"cors" yaml:"cors" envPrefix:"CORS_"`
8470

8571
// 解析后的数据
86-
maxHeaderBytes uint64
87-
log *zerolog.Logger
88-
server *http.Server
89-
routerBuilders map[WEB_FRAMEWORK]RouterBuilder `json:"-" yaml:"-" toml:"-" env:"-"`
90-
handlerCount map[WEB_FRAMEWORK]int `json:"-" yaml:"-" toml:"-" env:"-"`
91-
RouterBuildConfig *BuildConfig `json:"-" yaml:"-" toml:"-" env:"-"`
72+
maxHeaderBytes uint64
73+
log *zerolog.Logger
74+
server *http.Server
75+
routerBuilders map[WEB_FRAMEWORK]RouterBuilder `json:"-" yaml:"-" toml:"-" env:"-"`
76+
handlerCount map[WEB_FRAMEWORK]int `json:"-" yaml:"-" toml:"-" env:"-"`
9277
}
9378

9479
func (h *Http) HTTPPrefix() string {
@@ -99,17 +84,6 @@ func (h *Http) HTTPPrefix() string {
9984
return u
10085
}
10186

102-
type HealthCheck struct {
103-
Enabled bool `toml:"enabled" json:"enabled" yaml:"enabled" env:"ENABLED"`
104-
}
105-
106-
type CORS struct {
107-
Enabled bool `toml:"enabled" json:"enabled" yaml:"enabled" env:"ENABLED"`
108-
AllowedHeaders []string `json:"cors_allowed_headers" yaml:"cors_allowed_headers" toml:"cors_allowed_headers" env:"ALLOWED_HEADERS" envSeparator:","`
109-
AllowedDomains []string `json:"cors_allowed_domains" yaml:"cors_allowed_domains" toml:"cors_allowed_domains" env:"ALLOWED_DOMAINS" envSeparator:","`
110-
AllowedMethods []string `json:"cors_allowed_methods" yaml:"cors_allowed_methods" toml:"cors_allowed_methods" env:"ALLOWED_METHODS" envSeparator:","`
111-
}
112-
11387
type WEB_FRAMEWORK string
11488

11589
const (
@@ -119,20 +93,6 @@ const (
11993
WEB_FRAMEWORK_GIN WEB_FRAMEWORK = "gin"
12094
)
12195

122-
type RouterBuilder interface {
123-
Config(*BuildConfig)
124-
Build() (http.Handler, error)
125-
}
126-
127-
type BuildHook func(http.Handler)
128-
129-
type BuildConfig struct {
130-
// 装载Ioc路由之前
131-
BeforeLoad BuildHook `json:"-" yaml:"-" toml:"-" env:"-"`
132-
// 装载Ioc路由之后
133-
AfterLoad BuildHook `json:"-" yaml:"-" toml:"-" env:"-"`
134-
}
135-
13696
func (h *Http) setEnable(v bool) {
13797
h.Enable = &v
13898
}
@@ -213,9 +173,6 @@ func (h *Http) BuildRouter() error {
213173
return fmt.Errorf("router builder for web framework %s not found", h.WEB_FRAMEWORK)
214174
}
215175

216-
// 传递配置
217-
rb.Config(h.RouterBuildConfig)
218-
219176
r, err := rb.Build()
220177
if err != nil {
221178
return err

0 commit comments

Comments
 (0)