go - 允许使用 gorilla 处理程序的来源

标签 go cross-domain gorilla

我目前正在编写一个安静的网络服务器,我想从 angular2 前端进行测试。由于在开发时服务器托管在另一个域上,我需要 Access-Control-Allow-Origin: * (我认为)。我尝试通过使用 gorilla handlers 包来实现这一点,即以下内容:

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

现在尝试使用以下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

我在服务器上收到一个 OPTIONS 请求,该请求返回 403。我还尝试添加 header 和允许的方法:

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

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

最佳答案

这对我有用:

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

您的curl示例中的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

关于go - 允许使用 gorilla 处理程序的来源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42153963/

相关文章:

rest - 当某些字段为只读而其他字段可为空时,如何使用 Golang 结构在 API 中执行 CRUD?

silverlight - Http 托管 silverlight 应用跨域访问 https 托管服务

visual-studio-2010 - 需要来自非域计算机的域帐户的测试代码

amazon-web-services - 有多个子域引用没有 HTTP 重定向的同一个 S3 存储桶

session - Gorilla session 不会在 Golang 中持续存在

session - Echo session 中间件不保存

go - golang中使用bufio.Scanner时如何继续执行程序

asynchronous - 处理条件异步函数的返回数据的惯用方法是什么?

git - 使用 git 设置正确的 Golang 目录结构以在自定义包上使用 go build

go - 从 router.HandleFunc 调用返回多个中间件函数