forked from st3v/go-plugins
/
cors.go
89 lines (75 loc) · 1.98 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package cors
import (
"net/http"
"strings"
"github.com/micro/cli"
"github.com/micro/micro/plugin"
"github.com/rs/cors"
)
type allowedCors struct {
allowedHeaders []string
allowedOrigins []string
allowedMethods []string
}
func (ac *allowedCors) Flags() []cli.Flag {
return []cli.Flag{
cli.StringFlag{
Name: "cors-allowed-headers",
Usage: "Comma-seperated list of allowed headers",
EnvVar: "CORS_ALLOWED_HEADERS",
},
cli.StringFlag{
Name: "cors-allowed-origins",
Usage: "Comma-seperated list of allowed origins",
EnvVar: "CORS_ALLOWED_ORIGINS",
},
cli.StringFlag{
Name: "cors-allowed-methods",
Usage: "Comma-seperated list of allowed methods",
EnvVar: "CORS_ALLOWED_METHODS",
},
}
}
func (ac *allowedCors) Commands() []cli.Command {
return nil
}
func (ac *allowedCors) Handler() plugin.Handler {
return func(ha http.Handler) http.Handler {
hf := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ha.ServeHTTP(w, r)
})
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cors.New(cors.Options{
AllowedOrigins: ac.allowedOrigins,
AllowedMethods: ac.allowedMethods,
AllowedHeaders: ac.allowedHeaders,
AllowCredentials: true,
}).ServeHTTP(w, r, hf)
})
}
}
func (ac *allowedCors) Init(ctx *cli.Context) error {
ac.allowedHeaders = ac.parseAllowed(ctx, "cors-allowed-headers")
ac.allowedMethods = ac.parseAllowed(ctx, "cors-allowed-methods")
ac.allowedOrigins = ac.parseAllowed(ctx, "cors-allowed-origins")
return nil
}
func (ac *allowedCors) parseAllowed(ctx *cli.Context, flagName string) []string {
fv := ctx.String(flagName)
// no op
if len(fv) == 0 {
return nil
}
return strings.Split(fv, ",")
}
func (ac *allowedCors) String() string {
return "cors-allowed-(headers|origins|methods)"
}
// NewPlugin Creates the CORS Plugin
func NewPlugin() plugin.Plugin {
return &allowedCors{
allowedHeaders: []string{},
allowedOrigins: []string{},
allowedMethods: []string{},
}
}