Search code examples
gogorilla

WebSocket returning 403 every time



I'm not sure why this error keeps occurring but when I try connecting in my web browser it fails and returns 403, but it doesn't make sense since no where in my code I specifically told it to return 403, and no middleware is involved, I attached a picture of the error im getting. Im also using Gorilla websocket with gin, here is my code that hosts it

func WebsocketServer(w http.ResponseWriter, r *http.Request, context *gin.Context) {
    fmt.Println("connection received")
    var upgrader2 = websocket.Upgrader{
        CheckOrigin: func(r *http.Request) bool {
            return true
        },
        EnableCompression: false,
    }
    db, err := aws.GetDB()
    if err != nil {
        helpers.Log.Println(err)
        return
    }
    defer db.Close()
    c, err := upgrader2.Upgrade(w, r, nil)
    if err != nil {
        helpers.Log.Println(err)
        return
    }

}
func PublicRoutes(c *gin.RouterGroup) {
    c.GET("/ws", func(c *gin.Context) {
        relay.WebsocketServer(c.Writer, c.Request, c)
    })
}

Im using aws to host this, is it a hosting issue?

[GIN] 2023/05/07 - 22:18:49 | 403 | 18.344µs | 71.121.188.229 | GET "/ws"


Solution

  • This issue is no longer a problem, it seemed to be an issue with my CORS? I fixed it by moving the configuration to the bottom. I should've put this code in my intial question

    Before

    router := gin.Default()
    config2 := cors.DefaultConfig()
        config2.AllowOrigins = []string{"http://localhost:3000", "https://rblxfortune.vercel.app", "https://bloxbet.click", "http://localhost:80"}
        config2.AllowCredentials = true
        router.Use(cors.New(config2))
    
        HandleRoutes(router)
        public := router.Group("/")
        routes.PublicRoutes(public)
        router.NoRoute(func(c *gin.Context) {
            http.Redirect(c.Writer, c.Request, "/login", http.StatusMovedPermanently)
        })
        private := router.Group("/")
        private.Use(helpers.AuthRequired)
        routes.PrivateRoutes(private)
        
        err := router.Run(config.Port)
        if err != nil {
            log.Println(err)
        }
    

    After

    router := gin.Default()
    
        HandleRoutes(router)
        public := router.Group("/")
        routes.PublicRoutes(public)
        router.NoRoute(func(c *gin.Context) {
            http.Redirect(c.Writer, c.Request, "/login", http.StatusMovedPermanently)
        })
        private := router.Group("/")
        private.Use(helpers.AuthRequired)
        routes.PrivateRoutes(private)
        config2 := cors.DefaultConfig()
        config2.AllowOrigins = []string{"http://localhost:3000", "https://rblxfortune.vercel.app", "https://bloxbet.click", "http://localhost:80"}
        config2.AllowCredentials = true
        router.Use(cors.New(config2))
        err := router.Run(config.Port)
        if err != nil {
            log.Println(err)
        }