Home > Backend Development > Golang > Websocket server implementation using x/net library trowing 403

Websocket server implementation using x/net library trowing 403

WBOY
Release: 2024-02-13 17:03:08
forward
979 people have browsed it

使用 x/net 库 trowing 403 的 Websocket 服务器实现

php editor Banana will introduce you to a method using the x/net library to implement a Websocket server that throws a 403 error. Websocket is a communication protocol that establishes a persistent connection between a client and a server, and a 403 error means that the server rejected the client's request. By using the x/net library, we can easily create a Websocket server and reject requests by throwing a 403 error when needed. This method is simple and effective, and is suitable for scenarios where requests need to be authorized or access restricted.

Question content

I am trying to implement a websocket server using the x/net/websocket standard library.

My attempts so far are as follows:

package main

import (
    "fmt"
    "net/http"

    "golang.org/x/net/websocket"
)

type Server struct {
    baseUri     string
    connections map[string][]*websocket.Conn
}

func initServer(baseUri string) *Server {
    return &Server{
        baseUri: baseUri,
    }
}

func (server *Server) handleConnections() {
    http.Handle("/ws", websocket.Handler(server.listenConnections))
    http.ListenAndServe(":3000", nil)
}

func (server *Server) listenConnections(ws *websocket.Conn) {
    fmt.Println("New connection established")
    for {
        fmt.Println("FOO")
    }
}

func main() {
    server := initServer("/ws")
    server.handleConnections()
}

Copy after login

When trying to connect to ws://localhost:3000/ws using multiple ws clients, I always get the same error: 403-Forbidden. I even tried the example from the official documentation but still get it. Am I missing something obvious? Like default port blocking or something like that?

Thank you in advance.

EDIT: You may need to use a different port to reproduce the issue. Using 3000 in my example will just interrupt the execution of the program if it is not available.

Edit 2: You can use a client like websocat and execute websocat 'ws://localhost:3000/ws' to try to connect to the server

Workaround

I gave up, but had good insights: If you're like me and are following Anthony GG's Walkthrough of Creating a Websocket Server on Go from Scratch, don't. Video is outdated, and while it provides a good intuition on how to create videos, it's best (and no shame) to learn using gorilla's websocket library.

package main

import (
    "fmt"
    "net/http"
    "time"

    "github.com/gorilla/mux"
    "github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
}

type Server struct {
    baseUri     string
    connections map[string][]*websocket.Conn
    router      *mux.Router
    setup       *http.Server
}

func initServer(baseUri string) *Server {
    router := mux.NewRouter()
    return &Server{
        baseUri: baseUri,
        router:  router,
        setup: &http.Server{
            Handler:      router,
            Addr:         "127.0.0.1:8000",
            WriteTimeout: 15 * time.Second,
            ReadTimeout:  15 * time.Second,
        },
    }
}

func (server *Server) handleConnections() {
    server.router.HandleFunc("/ws/{var}", server.listenConnections)
    server.setup.ListenAndServe()
}

func (server *Server) listenConnections(w http.ResponseWriter, r *http.Request) {
    connection, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        fmt.Println(err)
        return
    }
    for {
        _, message, err := connection.ReadMessage()
        if err != nil {
            break
        }

        connection.WriteMessage(websocket.TextMessage, message)
        go messageHandler(message)
    }
    fmt.Println("Out of loop")
}

func messageHandler(message []byte) {
    fmt.Println(string(message))
}

func main() {
    server := initServer("/ws")
    server.handleConnections()
}

Copy after login

I also used gorilla/mux to use path parameters (not sure why the http handler can't). Notice how I changed http.Handle to mux.Router.HandleFunc. As user @Cerise pointed out in the comments, the x/net/websocket package is not in the standard library, but just adding the Origin header didn't solve the original problem either.

Hopefully this saves some of the trouble others like me running into when learning Go.

The above is the detailed content of Websocket server implementation using x/net library trowing 403. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template