You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
1.6 KiB

2 years ago
package cors
2 years ago
import (
"context"
12 months ago
"fmt"
2 years ago
"git.diulo.com/mogfee/kit/middleware"
"git.diulo.com/mogfee/kit/transport"
1 year ago
"net/http"
2 years ago
)
type OptionFunc func(o *option)
func WithDomain(domain string) OptionFunc {
return func(o *option) {
o.domain = domain
}
}
func WithMethod(method string) OptionFunc {
return func(o *option) {
o.method = method
}
}
func WithHeader(header string) OptionFunc {
return func(o *option) {
o.headers = header
}
}
type option struct {
domain string
method string
headers string
}
func Cors(ops ...OptionFunc) middleware.Middleware {
cfg := &option{
domain: "*",
method: "GET,POST,OPTIONS,PUT,PATCH,DELETE",
headers: "Content-Type,X-Requested-With,Access-Control-Allow-Credentials,User-Agent,Content-Length,Authorization",
}
for _, o := range ops {
o(cfg)
}
return func(handler middleware.Handler) middleware.Handler {
return func(ctx context.Context, a any) (any, error) {
if tr, ok := transport.FromServerContext(ctx); ok {
header := tr.ReplyHeader()
header.Set("Access-Control-Allow-Origin", cfg.domain)
header.Set("Access-Control-Allow-Methods", cfg.method)
header.Set("Access-Control-Allow-Credentials", "true")
header.Set("Access-Control-Allow-Headers", cfg.headers)
}
return handler(ctx, a)
}
}
}
1 year ago
func HttpServer() func(http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
ch := &cors{h: h}
ch.h = h
return ch
}
}
type cors struct {
h http.Handler
}
func (ch *cors) ServeHTTP(w http.ResponseWriter, r *http.Request) {
12 months ago
fmt.Println("cors start")
1 year ago
ch.h.ServeHTTP(w, r)
12 months ago
fmt.Println("cors end")
1 year ago
}