Golang: 解決 Go Websocket upgrade:websocket: request origin not allowed by Upgrader.CheckOrigin 跨域問題

錯誤訊息:

upgrade:websocket: request origin not allowed by Upgrader.CheckOrigin

原因: 如內文所述,在 Go Websocket 判別跨域來源不合法

解決方式: 需要在 websocket.Upgrader 設定 CheckOrigin 來源,例如下方允許所有來源

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
} // use default options

例如,在使用 Chrome Websocket King Client 擴充時,可以只允許這個來源,例如:

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		origin := r.Header.Get("Origin")
		return origin == "chrome-extension://cbcbkhdmedgianpaifchdaddpnmgnknn"
	},
}