跨域,简称CROS,Cross-origin resource sharing。这里不仅仅是golang开发http server时会遇到的问题,它不区分语言,只要是http server都可能遇到这个问题。
本文介绍跨域的通用解决办法。

一个简单的golang http server

hello, world
package main

import "net/http"

func HandlerHttp(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("hello, world"))
}

func main() {
	http.HandleFunc("/", HandlerHttp)
	http.ListenAndServe("127.0.0.1:8888", nil)
}
http://127.0.0.1:8888hello, world

跨域访问问题

跨域访问是指当请求地址与http服务器地址或端口不一致时,且请求为XMLHttpRequest请求,也就是ajax访问。

跨域问题是浏览器对于ajax请求的一种安全限制:一个页面发起的ajax请求,只能是与当前页域名相同的路径,这能有效的阻止跨站攻击。因此,跨域问题 是针对ajax的一种限制。

我们在访问某个网页的浏览器窗口上,进入浏览器开发者模式下,执行一个XMLHttpRequest请求

req = new XMLHttpRequest()
req.open('get', 'http://127.0.0.1:8888', true)
req.send()
已拦截跨源请求:同源策略禁止读取位于 http://127.0.0.1:8888/ 的远程资源。(原因:CORS 头缺少 'Access-Control-Allow-Origin')。状态码:200。

服务端解决办法

Access-Control-Allow-OriginHandlerHttp

为了更通用,还需要处理OPTIONS类型http请求,所以通用的一个处理方式如下所示:

package main

import "net/http"

func setupCORS(w *http.ResponseWriter) {
	(*w).Header().Set("Access-Control-Allow-Origin", "*")
	(*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
	(*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}

func HandlerHttp(w http.ResponseWriter, r *http.Request) {
	setupCORS(&w)
	if r.Method == "OPTIONS" {
		return
	}
	w.Write([]byte("hello, world"))
}

func main() {
	http.HandleFunc("/", HandlerHttp)
	http.ListenAndServe("127.0.0.1:8888", nil)
}

修改后,使用XMLHttpRequest方式访问网页正常返回结果。

参考资料