Search code examples
gowebsocketgorilla

How to add a trusted origin to gorilla websocket's CheckOrigin?


I'm developing a websocket-based app where the frontend is in vue.js running on port 127.0.0.1:8080 and the backend is in golang running on port 127.0.0.1:3000. The frontend is suppose to communicates to: serverUrl: "ws://127.0.0.1:3000/ws",

To avoid CORS problem I had to return true for CheckOrigin:

var upgrader = websocket.Upgrader{
    ReadBufferSize:  4096,
    WriteBufferSize: 4096,
    CheckOrigin: func(r *http.Request) bool {
        return true
    },
}

However I know that it is not secure bacuase this leaves the door open to any IP to connect to backed. My question is that how can I limit it so that it only allows request from 127.0.0.1:8080 ?

I've looked at the docs but could not find how to do so.


Solution

  • Return true from the CheckOrigin function if the origin is the trusted site.

    CheckOrigin: func(r *http.Request) bool {
        origin := r.Header.Get("Origin")
        return origin == "http://127.0.0.1:8080"
    },