From a9dd611deb5d227c6d93bc78ec24de9350887e0d Mon Sep 17 00:00:00 2001 From: Giancarlos Salas Date: Mon, 16 May 2022 11:17:08 -0500 Subject: [PATCH] Add cors support --- README.md | 6 ++++++ cmd/main.go | 15 ++++++++++++++- go.mod | 1 + go.sum | 2 ++ 4 files changed, 23 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 8f0bf21..8d7e659 100644 --- a/README.md +++ b/README.md @@ -11,3 +11,9 @@ make build ./build/gnoapi ``` + +Custom port and cors enabled. + +``` +./build/gnoapi --port 1317 --cors +``` \ No newline at end of file diff --git a/cmd/main.go b/cmd/main.go index 4a9ee0b..00d91fb 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -9,6 +9,7 @@ import ( "github.com/gnolang/gno/pkgs/bft/rpc/client" "github.com/gorilla/mux" + "github.com/rs/cors" "github.com/disperze/gno-api/cmd/handler" @@ -19,6 +20,7 @@ import ( var ( remotePtr = flag.String("remote", "http://gno.land:36657", "Remote rpc") apiPortPtr = flag.String("port", "8888", "Api port") + corsPtr = flag.Bool("cors", false, "Enable CORS") ) func main() { @@ -32,6 +34,12 @@ func main() { log.Fatal("api port is required") } + c := cors.New(cors.Options{ + AllowedOrigins: []string{"*"}, + AllowedMethods: []string{http.MethodGet, http.MethodPost}, + AllowedHeaders: []string{"Content-Type", "Accept"}, + }) + apiPort := *apiPortPtr cli := client.NewHTTP(*remotePtr, "/websocket") @@ -45,6 +53,11 @@ func main() { r.HandleFunc("/txs/decode", handler.TxDecodeHandler(cli)).Methods(http.MethodGet) r.HandleFunc("/txs", handler.TxsHandler(cli)).Methods(http.MethodPost) + var h http.Handler = r + if *corsPtr { + h = c.Handler(r) + } + fmt.Println("Running on port", apiPort) - log.Fatal(http.ListenAndServe(":"+apiPort, r)) + log.Fatal(http.ListenAndServe(":"+apiPort, h)) } diff --git a/go.mod b/go.mod index 0a3a6e5..c097cf3 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.17 require ( github.com/gnolang/gno v0.0.0-20220505214555-31c139670944 github.com/gorilla/mux v1.8.0 + github.com/rs/cors v1.8.2 ) require ( diff --git a/go.sum b/go.sum index f2a9644..b41ea88 100644 --- a/go.sum +++ b/go.sum @@ -78,6 +78,8 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rs/cors v1.8.2 h1:KCooALfAYGs415Cwu5ABvv9n9509fSiG5SQJn/AQo4U= +github.com/rs/cors v1.8.2/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=