2017-02-10 41 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