Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

get a error when I using "github.com/iris-contrib/middleware/cors" #60

Open
roderick-liu opened this issue Jul 29, 2020 · 1 comment
Open
Labels

Comments

@roderick-liu
Copy link

go version go1.14.4 linux/amd64
programe:
package main

import (
"fmt"
"github.com/iris-contrib/middleware/cors"
"log"
"net"
"os"
)

func main() {
fmt.Println("Hello World!")
fmt.Println(os.Getuid())
f, err := os.Open("test.json")
if err != nil {
fmt.Printf("%s\n", err)
}
crs := cors.New(cors.Options{
AllowedOrigins: []string{"*"}, // allows everything, use that to change the hosts.
AllowCredentials: true,
})

}
error :
$ go build hello.go

github.com/iris-contrib/middleware/cors

gowork/src/github.com/iris-contrib/middleware/cors/cors.go:144:10: cannot use c.Serve (type func("github.com/kataras/iris/context".Context)) as type "github.com/kataras/iris/context".Handler in return argument

otherwise:
in go.mod:
there is a conflict between
github.com/iris-contrib/middleware v12.1.2+incompatible and import github.com/iris-contrib/middleware/cors

@kataras
Copy link
Member

kataras commented Aug 9, 2020

Hello @roderick-liu, this is happening because you've tried to install the stable version with the master version of Iris, the middleware should be installed using the @master suffix, just like master version of Iris. To solve the issue, please follow the stpes below:

$ go mod init myapp
$ go get github.com/kataras/iris/v12@master
$ go get github.com/iris-contrib/middleware/cors@master

Example App

server

package main

import (
	"github.com/kataras/iris/v12"

	"github.com/iris-contrib/middleware/cors"
)

func main() {
	app := iris.New()

	crs := cors.New(cors.Options{
		AllowedOrigins:   []string{"*"}, // allows everything, use that to change the hosts.
		AllowCredentials: true,
	})

	/* OR just:
		crs := func(ctx iris.Context) {
		ctx.Header("Access-Control-Allow-Origin", "*")
		ctx.Header("Access-Control-Allow-Credentials", "true")

		if ctx.Method() == iris.MethodOptions {
			ctx.Header("Access-Control-Methods", "POST, PUT, PATCH, DELETE")
			ctx.Header("Access-Control-Allow-Headers", "Access-Control-Allow-Origin,Content-Type")
			ctx.Header("Access-Control-Max-Age", "86400")
			ctx.StatusCode(iris.StatusNoContent)
			return
		}

		ctx.Next()
	}
	*/

	v1 := app.Party("/api/v1", crs).AllowMethods(iris.MethodOptions) // <- important for the preflight.
	{
		v1.Post("/mailer", func(ctx iris.Context) {
			var any iris.Map
			err := ctx.ReadJSON(&any)
			if err != nil {
				ctx.StopWithError(iris.StatusBadRequest, err)
				return
			}
			ctx.Application().Logger().Infof("received %#+v", any)

			ctx.JSON(iris.Map{"message": "ok"})
		})

		v1.Get("/home", func(ctx iris.Context) {
			ctx.WriteString("Hello from /home")
		})
		v1.Get("/about", func(ctx iris.Context) {
			ctx.WriteString("Hello from /about")
		})
		v1.Post("/send", func(ctx iris.Context) {
			ctx.WriteString("sent")
		})
		v1.Put("/send", func(ctx iris.Context) {
			ctx.WriteString("updated")
		})
		v1.Delete("/send", func(ctx iris.Context) {
			ctx.WriteString("deleted")
		})
	}

	app.Listen(":8080", iris.WithTunneling)
}

server/go.mod

module myapp

go 1.14

require github.com/iris-contrib/middleware/cors v0.0.0-20200710202437-92b01b85baaf

client

package main

import "github.com/kataras/iris/v12"

func main() {
	app := iris.New()
	app.Get("/", func(ctx iris.Context) {
		ctx.ServeFile("index.html")
	})

	// Navigate to http://localhost:9090,
	// this will act as a client for your server.
	// Don't forget to EDIT the index.html's host variable
	// to match the server's one.
	app.Listen(":9090")
}
<body>
    <script type="text/javascript">
        // Replace the "host" with your domain (you can use iris.WithTunneling).
        const host = 'https://b6fbe7259b4f.ngrok.io';

        async function postData(url = '', data = {}) {
            const response = await fetch(url, {
                method: 'POST',
                mode: 'cors',
                cache: 'no-cache',
                credentials: 'same-origin',
                headers: {
                    'Content-Type': 'application/json'
                },
                redirect: 'follow',
                referrerPolicy: 'no-referrer',
                body: JSON.stringify(data)
            });
            return response.json();
        }

        postData(host + '/api/v1/mailer', {
                email: "me@test.com"
            })
            .then(data => {
                console.log(data);
                document.write(data.message);
            });
    </script>
</body>

output

image

Notes

  1. As of the latest Iris commit you can use the app.UseRouter if you need to register it globally, it enables all its features without the requirement of AllowMethods.
app.UseRouter(crs)
  1. Another example can be found at: _examples/auth/cors which uses the rs/cors middleware and registers it, globally, via app.WrapRouter (same as app.UseRouter but it accepts standard net/http middlewares instead).

Thanks,
Gerasimos Maropoulos.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants