From b39cfebca793973280f64db6a2932b712d89a41b Mon Sep 17 00:00:00 2001 From: langhuihui <178529795@qq.com> Date: Wed, 9 Oct 2024 17:20:17 +0800 Subject: [PATCH] fix: add cors to grpc gateway --- server.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/server.go b/server.go index 4bfdce3..18a2f47 100644 --- a/server.go +++ b/server.go @@ -14,6 +14,7 @@ import ( "time" "github.com/shirou/gopsutil/v3/cpu" + "google.golang.org/protobuf/proto" "m7s.live/m7s/v5/pkg/task" @@ -179,7 +180,15 @@ func (s *Server) Start() (err error) { s.LogHandler.SetLevel(slog.LevelDebug) s.LogHandler.Add(defaultLogHandler) s.Logger = slog.New(&s.LogHandler).With("server", s.ID) - mux := runtime.NewServeMux(runtime.WithMarshalerOption("text/plain", &pb.TextPlain{}), runtime.WithRoutingErrorHandler(func(_ context.Context, _ *runtime.ServeMux, _ runtime.Marshaler, w http.ResponseWriter, r *http.Request, _ int) { + mux := runtime.NewServeMux(runtime.WithMarshalerOption("text/plain", &pb.TextPlain{}), runtime.WithForwardResponseOption(func(ctx context.Context, w http.ResponseWriter, m proto.Message) error { + header := w.Header() + header.Set("Access-Control-Allow-Credentials", "true") + header.Set("Cross-Origin-Resource-Policy", "cross-origin") + header.Set("Access-Control-Allow-Headers", "Content-Type,Access-Token") + header.Set("Access-Control-Allow-Private-Network", "true") + header.Set("Access-Control-Allow-Origin", "*") + return nil + }), runtime.WithRoutingErrorHandler(func(_ context.Context, _ *runtime.ServeMux, _ runtime.Marshaler, w http.ResponseWriter, r *http.Request, _ int) { httpConf.GetHttpMux().ServeHTTP(w, r) })) httpConf.SetMux(mux)