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

1

7

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.

Fourier answered 27/11, 2020 at 8:31 Comment(0)
S
13

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"
},
Sweetie answered 27/11, 2020 at 15:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.