middleware can't be apply on a router group
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))
}
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
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.
This issue took more than 2 hours of my time. The @yashmurty's solution works for me but not in all cases :man_facepalming:
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.
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.