在Golang回调函数中启用CORS

时间:2015-04-02 08:34:48

标签: javascript ajax go cors

我对Google的oAuth2 api进行了AJAX调用,如下所示:

$(document).on('click', '#signup', function() {
  var OAUTHURL        =  'https://accounts.google.com/o/oauth2/auth?';
  var SCOPE           =   'email profile';
  var STATE           =   'profile';
  var REDIRECT_URI    =   'https://localhost:8080/callback';
  var RESPONSE_TYPE   =   'token';
  var CLIENT_ID       =   '554886359117-8icq0dc9halr8rjd6bdtqcmagrdql9lr.apps.googleusercontent.com';
  var _url            =    OAUTHURL + 'scope=' + SCOPE + '&state=' + STATE + '&redirect_uri=' + REDIRECT_URI + '&response_type=' + RESPONSE_TYPE + '&client_id=' + CLIENT_ID;
  $.ajax({
    type: "POST",
    dataType: "text",
    url: _url,
    success: function(response)
    {
        console.log(response.url);
    },
    error: function(error)
    {
        console.log("ERROR: ", error);
    }
  });
});

这应该重定向回http://localhost/callback上运行的服务器。

Redirect URIs:  http://localhost:8080/callback
Javascript Origins: http://localhost:8080

我还有如下定义的回调函数:

func init() {
    r := mux.NewRouter()

    r.HandleFunc("/", rootHandler)
    r.HandleFunc("/callback", callbackHandler)
    http.Handle("/", r)
}
func callbackHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "I am sent back from the server!"+time.Now().Format("Mon, 02 Jan 2006 15:04:05 MST"))
}

在调试模式下一切看起来都不错,除了我从google的api中得到这个错误:

  

XMLHttpRequest无法加载   https://accounts.google.com/o/oauth2/auth?scope=email%20profile&state=profi ... d = 554886359117-8icq0dc9halr8rjd6bdtqcmagrdql9lr.apps.googleusercontent.com。   请求中不存在“Access-Control-Allow-Origin”标头   资源。因此不允许来源“http://localhost:8080”   访问。

我已经调整了一下,但我似乎无法找到自己的方法。 有没有想过这个?

2 个答案:

答案 0 :(得分:1)

与Not_a_Golfer一样,您的后端未设置正确的标头以进行响应。为了在每种情况下处理CORS问题,我创建了包含路由器的小handler,这样您就不必在每次回调中手动设置标头。

像这样使用:

import "github.com/heppu/simple-cors"

func init() {
    r := mux.NewRouter()
    r.HandleFunc("/", rootHandler)
    r.HandleFunc("/callback", callbackHandler)
    http.Handle("/", cors.CORS(r))
}
func callbackHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "I am sent back from the server!"+time.Now().Format("Mon, 02 Jan 2006 15:04:05 MST"))
}

答案 1 :(得分:0)

只需将CORS标头添加到您的callbackHandler:

// make this configurable via command line flags, env var, or something
var MyServerName = "https://localhost:8080" 

func callbackHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Add("Access-Control-Allow-Origin", MyServerName)

    fmt.Fprint(w, "I am sent back from the server!"+time.Now().Format("Mon, 02 Jan 2006 15:04:05 MST"))
}