/
cors.go
66 lines (55 loc) · 1.64 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 plugins
import (
"encoding/json"
"log"
"net/http"
"github.com/movio/bramble"
"github.com/rs/cors"
"github.com/sirupsen/logrus"
)
func init() {
bramble.RegisterPlugin(&CorsPlugin{})
}
type CorsPlugin struct {
bramble.BasePlugin
config CorsPluginConfig
}
type CorsPluginConfig struct {
AllowedOrigins []string `json:"allowed-origins"`
AllowedHeaders []string `json:"allowed-headers"`
AllowedMethods []string `json:"allowed-methods"`
AllowCredentials bool `json:"allow-credentials"`
ExposedHeaders []string `json:"exposed-headers"`
MaxAge int `json:"max-age"`
Debug bool `json:"debug"`
}
func NewCorsPlugin(options CorsPluginConfig) *CorsPlugin {
return &CorsPlugin{bramble.BasePlugin{}, options}
}
func (p *CorsPlugin) ID() string {
return "cors"
}
func (p *CorsPlugin) Configure(cfg *bramble.Config, data json.RawMessage) error {
return json.Unmarshal(data, &p.config)
}
func (p *CorsPlugin) middleware(h http.Handler) http.Handler {
c := cors.New(cors.Options{
AllowedOrigins: p.config.AllowedOrigins,
AllowedHeaders: p.config.AllowedHeaders,
AllowedMethods: p.config.AllowedMethods,
AllowCredentials: p.config.AllowCredentials,
ExposedHeaders: p.config.ExposedHeaders,
MaxAge: p.config.MaxAge,
Debug: p.config.Debug,
})
if p.config.Debug {
c.Log = log.New(logrus.StandardLogger().Writer(), "cors:", log.Lshortfile)
}
return c.Handler(h)
}
func (p *CorsPlugin) ApplyMiddlewarePublicMux(h http.Handler) http.Handler {
return p.middleware(h)
}
func (p *CorsPlugin) ApplyMiddlewarePrivateMux(h http.Handler) http.Handler {
return p.middleware(h)
}