Websocket server implementation using x/net library trowing 403
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() }
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() }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

There are two ways to obtain absolute values in C++: 1. Use the built-in function abs() to obtain the absolute value of an integer or floating point type; 2. Use the generic function std::abs() to obtain various supported absolute values. Operates on absolute values of data types.

std is the namespace in C++ that contains components of the standard library. In order to use std, use the "using namespace std;" statement. Using symbols directly from the std namespace can simplify your code, but is recommended only when needed to avoid namespace pollution.

There are two ways to create popups in Python: Tkinter: Use the Tkinter library to create Tk or TopLevel widgets. Pyglet: Use the Pyglet library to create Window windows.

prime is a keyword in C++, indicating the prime number type, which can only be divided by 1 and itself. It is used as a Boolean type to indicate whether the given value is a prime number. If it is a prime number, it is true, otherwise it is false.

Config represents configuration information in Java and is used to adjust application behavior. It is usually stored in external files or databases and can be managed through Java Properties, PropertyResourceBundle, Java Configuration Framework or third-party libraries. Its benefits include decoupling and flexibility. , environmental awareness, manageability, scalability.

The fabs() function is a mathematical function in C++ that calculates the absolute value of a floating point number, removes the negative sign and returns a positive value. It accepts a floating point parameter and returns an absolute value of type double. For example, fabs(-5.5) returns 5.5. This function works with floating point numbers, whose accuracy is affected by the underlying hardware.

The complex type is used to represent complex numbers in C language, including real and imaginary parts. Its initialization form is complex_number = 3.14 + 2.71i, the real part can be accessed through creal(complex_number), and the imaginary part can be accessed through cimag(complex_number). This type supports common mathematical operations such as addition, subtraction, multiplication, division, and modulo. In addition, a set of functions for working with complex numbers is provided, such as cpow, csqrt, cexp, and csin.

There are three ways to find the absolute value in C++: Using the abs() function, you can calculate the absolute value of any type of number. Using the std::abs() function, you can calculate the absolute value of integers, floating point numbers, and complex numbers. Manual calculation of absolute values, suitable for simple integers.
