当前仓库属于暂停状态,部分功能使用受限,详情请查阅 仓库状态说明
2 Star 0 Fork 1

JUMEI_ARCH / go-plugins
暂停

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
cors.go 1.98 KB
一键复制 编辑 原始数据 按行查看 历史
He Weiwei 提交于 2018-04-10 21:55 . new cors with options from flags
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{},
}
}
Go
1
https://gitee.com/JMArch/go-plugins.git
git@gitee.com:JMArch/go-plugins.git
JMArch
go-plugins
go-plugins
v0.12.0

搜索帮助