2017-02-10 46 views
1

我目前正在编写一个宁静的web服务器,我想从angular2前端进行测试。由于服务器托管在另一个域名,而开发我需要Access-Control-Allow-Origin: *(我认为)。我尝试用大猩猩处理程序包,即实现了以下内容:尝试使用下面的卷曲请求服务器时允许使用大猩猩处理程序的起源

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

现在:

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 

我得到一个选项在服务器上请求,它返回403.我也尝试添加标题和允许的方法:

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

但它没有区别。我该如何解决这个问题?

+0

如果你不能得到它的工作,答案在http://stackoverflow.com/questions/12830095/setting-http-headers-in-golang/24818638#24818638似乎是解决这个问题的方法 – sideshowbarker

+0

不幸的是,这样做不起作用,因为我也在使用gorilla mux路由器并设置函数方法,所以我必须单独包装每条路线 – tofiffe

回答

1

这个工作对我来说:

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)))) 
} 

X-Requested-With在你卷曲例如拼写错误:

$ 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