gin-contrib / cors

Official CORS gin's middleware
https://gin-gonic.github.io/gin/
MIT License
1.79k stars 186 forks source link

Example does not seem to work? #69

Closed vikkio88 closed 4 years ago

vikkio88 commented 4 years ago

Hello there, new to go so I am learning as I go sort of translating a small api app from other languages.

I will need to have cors, so rather than building my own middleware, I thought to give this a go, but looks like something is not working properly, maybe gin changed the way middlewares are provided? can't see anything around not even on the issues.

basically my code looks like this

package main

import (
    "net/http"

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

func main() {
    router := gin.Default()

    config := cors.DefaultConfig()
    config.AllowOrigins = []string{"*"}
    router.Use(cors.New(config))

    router.GET("/ping", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{
            "message": "pong",
        })
    })

    router.Run()
}

and I expect this to return the Allow Origins Headers, but I only get this

% http get http://localhost:8080/ping
HTTP/1.1 200 OK
Content-Length: 41
Content-Type: application/json; charset=utf-8
Date: Thu, 13 Aug 2020 11:54:48 GMT

{
    "message": "pong"
}

am I doing something wrong? In the example you can only see the middleware being Used by the router, not the example route, I tried to place it before, and after the middleware declaration, but still nothing.

What am I doing wrong? Maybe is worth updating the doc to showcase an example with a route call?

thanks in advance

vikkio88 commented 4 years ago

I went to dig on the code and found out that the middleware is applying cors only if the header Origin is setup on the request, that is why it want appearing by default.

% curl -H origin:somestuff.com localhost:3000/ping
...
Access-Control-Allow-Origin: *
...

so not a bug but a feature

vikkio88 commented 4 years ago

maybe is worth adding it on the docs, to avoid confusing newbies like myself