Skip to content

Commit a9dd611

Browse files
committed
Add cors support
1 parent 127f9d7 commit a9dd611

File tree

4 files changed

+23
-1
lines changed

4 files changed

+23
-1
lines changed

README.md

+6
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,9 @@ make build
1111
1212
./build/gnoapi
1313
```
14+
15+
Custom port and cors enabled.
16+
17+
```
18+
./build/gnoapi --port 1317 --cors
19+
```

cmd/main.go

+14-1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"github.com/gnolang/gno/pkgs/bft/rpc/client"
1010

1111
"github.com/gorilla/mux"
12+
"github.com/rs/cors"
1213

1314
"github.com/disperze/gno-api/cmd/handler"
1415

@@ -19,6 +20,7 @@ import (
1920
var (
2021
remotePtr = flag.String("remote", "http://gno.land:36657", "Remote rpc")
2122
apiPortPtr = flag.String("port", "8888", "Api port")
23+
corsPtr = flag.Bool("cors", false, "Enable CORS")
2224
)
2325

2426
func main() {
@@ -32,6 +34,12 @@ func main() {
3234
log.Fatal("api port is required")
3335
}
3436

37+
c := cors.New(cors.Options{
38+
AllowedOrigins: []string{"*"},
39+
AllowedMethods: []string{http.MethodGet, http.MethodPost},
40+
AllowedHeaders: []string{"Content-Type", "Accept"},
41+
})
42+
3543
apiPort := *apiPortPtr
3644
cli := client.NewHTTP(*remotePtr, "/websocket")
3745

@@ -45,6 +53,11 @@ func main() {
4553
r.HandleFunc("/txs/decode", handler.TxDecodeHandler(cli)).Methods(http.MethodGet)
4654
r.HandleFunc("/txs", handler.TxsHandler(cli)).Methods(http.MethodPost)
4755

56+
var h http.Handler = r
57+
if *corsPtr {
58+
h = c.Handler(r)
59+
}
60+
4861
fmt.Println("Running on port", apiPort)
49-
log.Fatal(http.ListenAndServe(":"+apiPort, r))
62+
log.Fatal(http.ListenAndServe(":"+apiPort, h))
5063
}

go.mod

+1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ go 1.17
55
require (
66
github.com/gnolang/gno v0.0.0-20220505214555-31c139670944
77
github.com/gorilla/mux v1.8.0
8+
github.com/rs/cors v1.8.2
89
)
910

1011
require (

go.sum

+2
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,8 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE
7878
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
7979
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
8080
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
81+
github.com/rs/cors v1.8.2 h1:KCooALfAYGs415Cwu5ABvv9n9509fSiG5SQJn/AQo4U=
82+
github.com/rs/cors v1.8.2/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=
8183
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
8284
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
8385
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=

0 commit comments

Comments
 (0)