cors icon indicating copy to clipboard operation
cors copied to clipboard

middleware can't be apply on a router group

Open jackielii opened this issue 7 years ago • 8 comments

The following gives 404:

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/http/httputil"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

func main() {
	router := gin.Default()
	c := cors.Default()
	var g gin.IRoutes
	g = router.Group("/")
	g = g.Use(c)
	g.GET("/", func(c *gin.Context) {
		c.String(200, "ok")
	})

	serve(router)
}

func serve(h http.Handler) {
	r := httptest.NewRequest(http.MethodOptions, "http://service.example.com", nil)
	r.Header.Set("Origin", "http://www.example.com")
	r.Header.Set("Access-Control-Request-Method", "POST")

	w := httptest.NewRecorder()
	h.ServeHTTP(w, r)
	b, _ := httputil.DumpResponse(w.Result(), true)
	fmt.Println(string(b))
}

jackielii avatar Jun 27 '18 16:06 jackielii

i think that's because you haven't define the e.OPTIONS("/", func(c *gin.Context) { ... }), your request method is OPTIONS, or maybe you can change it to GET

junral avatar Sep 03 '18 04:09 junral

As mentioned above, it is because there is no definition for OPTIONS.

You can solve it by :

	g.OPTIONS("/", func(c *gin.Context) {
		c.AbortWithStatus(204)
	})

@jackielii Please let me know if this solves your issue.

yashmurty avatar Jan 08 '19 13:01 yashmurty

This issue took more than 2 hours of my time. The @yashmurty's solution works for me but not in all cases :man_facepalming:

ahmdrz avatar Feb 13 '19 09:02 ahmdrz

Don't work for me either. @yashmurty suggestion only work if you set OPTION method for each route of your API. So, basically, don't work.

mqzabin avatar May 03 '21 18:05 mqzabin

Any progress on this issue? I think it should be fixed in Gin itself, though.

FWIW, gorilla/mux suffers from a similar problem; however, neither Chi nor Fiber nor Echo do.

jub0bs avatar Mar 26 '24 10:03 jub0bs