Websocket

Golang: Gin + Gorilla to build a websocket application

Here we used the gorilla module to build a websocket application, and this tutorial will focus on building up a websoccket server.

About client part will implement with the chrome extension: Websocket King.

Get gorilla module

go get github.com/gorilla/websocket

Build a websocket server

Following are examples of simple websocket servers built with gin and gorilla,

Gin creates a get request and upgrades this HTTP connection to websocket connection by upgrader.Upgrade.

Continue Reading

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

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"
	},
}

Continue Reading