-
-
Notifications
You must be signed in to change notification settings - Fork 93
/
cors.go
66 lines (57 loc) · 1.59 KB
/
cors.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package cors
import (
"github.com/bitmagnet-io/bitmagnet/internal/boilerplate/httpserver"
"github.com/gin-gonic/gin"
"github.com/rs/cors"
gincors "github.com/rs/cors/wrapper/gin"
"go.uber.org/fx"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"time"
)
type Params struct {
fx.In
Config httpserver.Config
Logger *zap.SugaredLogger
}
type Result struct {
fx.Out
Option httpserver.Option `group:"http_server_options"`
}
func New(p Params) Result {
config := p.Config.Cors
return Result{
Option: corsOption{gincors.New(cors.Options{
AllowedOrigins: config.AllowedOrigins,
AllowedMethods: config.AllowedMethods,
AllowedHeaders: config.AllowedHeaders,
ExposedHeaders: config.ExposedHeaders,
MaxAge: config.MaxAge,
AllowCredentials: config.AllowCredentials,
AllowPrivateNetwork: config.AllowPrivateNetwork,
OptionsPassthrough: config.OptionsPassthrough,
OptionsSuccessStatus: config.OptionsSuccessStatus,
Debug: config.Debug,
// we don't need every request logged so apply sampling
Logger: corsLogger{p.Logger.WithOptions(zap.WrapCore(func(core zapcore.Core) zapcore.Core {
return zapcore.NewSamplerWithOptions(core, time.Hour, 10, 0)
})).Named("cors")},
})},
}
}
type corsOption struct {
handlerFunc gin.HandlerFunc
}
func (corsOption) Key() string {
return "cors"
}
func (c corsOption) Apply(g *gin.Engine) error {
g.Use(c.handlerFunc)
return nil
}
type corsLogger struct {
logger *zap.SugaredLogger
}
func (c corsLogger) Printf(format string, v ...interface{}) {
c.logger.Debugf(format, v...)
}