2

I'm currently writing a restful web server, that I would like to test from angular2 frontend. Since the server is hosted on another domain while developing I need Access-Control-Allow-Origin: * (I think). I tried to achieve that by using the gorilla handlers package, namely the following:

origins := handlers.AllowedOrigins([]string{"*"})
log.Fatal(http.ListenAndServe(":"+os.Getenv(util.Port),
    handlers.LoggingHandler(os.Stdout, handlers.CORS(origins)(router))))

now when trying to request the server using the following curl:

curl -H "Origin: http://example.com" \
-H "Access-Control-Request-Method: POST" \
-H "Access-Control-Request-Headers: X-Requested-Width" \
-X OPTIONS --verbose localhost:8000

I get an OPTIONS request on the server, which returns 403. I have also tried adding headers and allowed methods:

handlers.AllowedHeaders([]string{"X-Requested-With"})
handlers.AllowedMethods([]string{"GET", "POST", "PUT", "OPTIONS"})

but it made no difference. How can I resolve this?

user_4685247
  • 2,878
  • 2
  • 17
  • 43
  • If you can’t get it working, the answer at http://stackoverflow.com/questions/12830095/setting-http-headers-in-golang/24818638#24818638 seems to be the way to work around it – sideshowbarker Feb 10 '17 at 11:40
  • unfortunately this won't work, since I'm also using gorilla mux router and set the function methods, so I'd have to wrap each route individually – user_4685247 Feb 10 '17 at 14:38

1 Answers1

2

This works for me:

package main

import (
    "log"
    "net/http"
    "os"

    "github.com/gorilla/handlers"
    "github.com/gorilla/mux"
)

func main() {
    router := mux.NewRouter()

    log.Fatal(http.ListenAndServe(":8080", 
        handlers.LoggingHandler(os.Stdout, handlers.CORS(
            handlers.AllowedMethods([]string{"POST"}),
            handlers.AllowedOrigins([]string{"*"}),
            handlers.AllowedHeaders([]string{"X-Requested-With"}))(router))))
}

The X-Requested-With is mistyped in your curl example:

$ curl -H "Origin: http://example.com" -H "Access-Control-Request-Method: POST" -H "Access-Control-Request-Headers: X-Requested-With" -X OPTIONS --verbose localhost:8080
* Rebuilt URL to: localhost:8080/
*   Trying ::1...
* Connected to localhost (::1) port 8080 (#0)
> OPTIONS / HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.50.1
> Accept: */*
> Origin: http://example.com
> Access-Control-Request-Method: POST
> Access-Control-Request-Headers: X-Requested-With
> 
< HTTP/1.1 200 OK
< Access-Control-Allow-Headers: X-Requested-With
< Access-Control-Allow-Origin: http://example.com
< Date: Thu, 16 Feb 2017 22:58:24 GMT
< Content-Length: 0
< Content-Type: text/plain; charset=utf-8
< 
* Connection #0 to host localhost left intact
Cristian Greco
  • 2,566
  • 1
  • 19
  • 24