go-zero icon indicating copy to clipboard operation
go-zero copied to clipboard

does gateway support cors config?

Open willis-yang opened this issue 11 months ago • 1 comments

#gateway main file package main

import ( "cloudPhoneGateway/pkg/gateway" "flag" "github.com/zeromicro/go-zero/core/conf" )

var configFile = flag.String("f", "etc/gateway.yaml", "config file")

func main() { flag.Parse() var c gateway.GatewayConf conf.MustLoad(*configFile, &c) gw := gateway.MustNewServer(c) defer gw.Stop() gw.Start()

}

willis-yang avatar Mar 21 '24 08:03 willis-yang

Not yet. Will work on it.

kevwan avatar Mar 29 '24 08:03 kevwan

I solved the cross-domain problem of gateway by adding the following code: image

axliupore avatar Jul 13 '24 11:07 axliupore

i had write a middle support that,

there is my code:

package middleware

import "net/http"

// CorsMiddleware
type CorsMiddleware struct {
}

// NewCorsMiddleware
func NewCorsMiddleware() *CorsMiddleware {
	return &CorsMiddleware{}
}

// Handle
func (m *CorsMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		setHeader(w)

		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusNoContent)
			return
		}

		next(w, r)
	}
}

// Handler
func (m *CorsMiddleware) Handler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		setHeader(w)

		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusNoContent)
		} else {
			w.WriteHeader(http.StatusNotFound)
		}
	})
}

// setHeader
func setHeader(w http.ResponseWriter) {
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Headers", "Content-Type, X-CSRF-Token, Authorization, AccessToken, Token")
	w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH")
	w.Header().Set("Access-Control-Expose-Headers", "Content-Length, Content-Type, Access-Control-Allow-Origin, Access-Control-Allow-Headers")
	w.Header().Set("Access-Control-Allow-Credentials", "true")
}

willis-yang avatar Jul 15 '24 02:07 willis-yang